aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.dockerignore4
-rw-r--r--.drone.yml28
-rw-r--r--.editorconfig133
-rw-r--r--.gitignore4
-rw-r--r--.vscode/launch.json28
-rw-r--r--.vscode/tasks.json15
-rw-r--r--CONTRIBUTORS.md16
-rw-r--r--Dockerfile20
-rw-r--r--Emby.Dlna/ConnectionManager/ConnectionManager.cs2
-rw-r--r--Emby.Dlna/ConnectionManager/ControlHandler.cs2
-rw-r--r--Emby.Dlna/ContentDirectory/ContentDirectory.cs2
-rw-r--r--Emby.Dlna/ContentDirectory/ControlHandler.cs6
-rw-r--r--Emby.Dlna/Didl/DidlBuilder.cs28
-rw-r--r--Emby.Dlna/DlnaManager.cs29
-rw-r--r--Emby.Dlna/Eventing/EventManager.cs8
-rw-r--r--Emby.Dlna/Images/logo120.jpgbin4134 -> 5337 bytes
-rw-r--r--Emby.Dlna/Images/logo120.pngbin2671 -> 7522 bytes
-rw-r--r--Emby.Dlna/Images/logo240.jpgbin10263 -> 11520 bytes
-rw-r--r--Emby.Dlna/Images/logo240.pngbin6468 -> 18287 bytes
-rw-r--r--Emby.Dlna/Images/logo48.jpgbin1580 -> 1839 bytes
-rw-r--r--Emby.Dlna/Images/logo48.pngbin932 -> 2554 bytes
-rw-r--r--Emby.Dlna/Main/DlnaEntryPoint.cs30
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs2
-rw-r--r--Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs2
-rw-r--r--Emby.Dlna/PlayTo/Device.cs18
-rw-r--r--Emby.Dlna/PlayTo/PlayToController.cs32
-rw-r--r--Emby.Dlna/PlayTo/PlayToManager.cs12
-rw-r--r--Emby.Dlna/Service/BaseControlHandler.cs16
-rw-r--r--Emby.Dlna/Service/BaseService.cs2
-rw-r--r--Emby.Dlna/Ssdp/DeviceDiscovery.cs6
-rw-r--r--Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj19
-rw-r--r--Emby.Drawing.ImageMagick/ImageHelpers.cs43
-rw-r--r--Emby.Drawing.ImageMagick/ImageMagickEncoder.cs354
-rw-r--r--Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs40
-rw-r--r--Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs125
-rw-r--r--Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs36
-rw-r--r--Emby.Drawing.ImageMagick/StripCollageBuilder.cs202
-rw-r--r--Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs73
-rw-r--r--Emby.Drawing.Net/DynamicImageHelpers.cs110
-rw-r--r--Emby.Drawing.Net/Emby.Drawing.Net.csproj17
-rw-r--r--Emby.Drawing.Net/GDIImageEncoder.cs282
-rw-r--r--Emby.Drawing.Net/ImageExtensions.cs217
-rw-r--r--Emby.Drawing.Net/ImageHelpers.cs43
-rw-r--r--Emby.Drawing.Net/PercentPlayedDrawer.cs34
-rw-r--r--Emby.Drawing.Net/PlayedIndicatorDrawer.cs32
-rw-r--r--Emby.Drawing.Net/Properties/AssemblyInfo.cs36
-rw-r--r--Emby.Drawing.Net/UnplayedCountIndicator.cs50
-rw-r--r--Emby.Drawing.Net/empty.pngbin68 -> 0 bytes
-rw-r--r--Emby.Drawing.Skia/SkiaEncoder.cs27
-rw-r--r--Emby.Drawing.Skia/StripCollageBuilder.cs25
-rw-r--r--Emby.Drawing/Common/ImageHeader.cs4
-rw-r--r--Emby.Drawing/Emby.Drawing.csproj2
-rw-r--r--Emby.Drawing/ImageProcessor.cs30
-rw-r--r--Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs118
-rw-r--r--Emby.IsoMounting/IsoMounter/LinuxMount.cs1
-rw-r--r--Emby.Notifications/NotificationManager.cs14
-rw-r--r--Emby.Notifications/Notifications.cs6
-rw-r--r--Emby.Photos/Emby.Photos.csproj2
-rw-r--r--Emby.Photos/PhotoProvider.cs6
-rw-r--r--Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs10
-rw-r--r--Emby.Server.Implementations/Activity/ActivityManager.cs7
-rw-r--r--Emby.Server.Implementations/Activity/ActivityRepository.cs232
-rw-r--r--Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs47
-rw-r--r--Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs22
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs494
-rw-r--r--Emby.Server.Implementations/Channels/ChannelManager.cs39
-rw-r--r--Emby.Server.Implementations/Channels/ChannelPostScanTask.cs4
-rw-r--r--Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs5
-rw-r--r--Emby.Server.Implementations/Collections/CollectionManager.cs31
-rw-r--r--Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs17
-rw-r--r--Emby.Server.Implementations/Data/BaseSqliteRepository.cs16
-rw-r--r--Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs8
-rw-r--r--Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs6
-rw-r--r--Emby.Server.Implementations/Data/SqliteItemRepository.cs32
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserDataRepository.cs4
-rw-r--r--Emby.Server.Implementations/Data/SqliteUserRepository.cs6
-rw-r--r--Emby.Server.Implementations/Devices/DeviceId.cs8
-rw-r--r--Emby.Server.Implementations/Devices/DeviceManager.cs12
-rw-r--r--Emby.Server.Implementations/Dto/DtoService.cs14
-rw-r--r--Emby.Server.Implementations/Emby.Server.Implementations.csproj4
-rw-r--r--Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs8
-rw-r--r--Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs21
-rw-r--r--Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs65
-rw-r--r--Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs6
-rw-r--r--Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs4
-rw-r--r--Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs8
-rw-r--r--Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs12
-rw-r--r--Emby.Server.Implementations/EntryPoints/StartupWizard.cs4
-rw-r--r--Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs7
-rw-r--r--Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs131
-rw-r--r--Emby.Server.Implementations/EntryPoints/UsageReporter.cs130
-rw-r--r--Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs2
-rw-r--r--Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs62
-rw-r--r--Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs2
-rw-r--r--Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs163
-rw-r--r--Emby.Server.Implementations/HttpServer/FileWriter.cs6
-rw-r--r--Emby.Server.Implementations/HttpServer/HttpListenerHost.cs36
-rw-r--r--Emby.Server.Implementations/HttpServer/HttpResultFactory.cs6
-rw-r--r--Emby.Server.Implementations/HttpServer/LoggerUtils.cs8
-rw-r--r--Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs4
-rw-r--r--Emby.Server.Implementations/HttpServer/ResponseFilter.cs4
-rw-r--r--Emby.Server.Implementations/HttpServer/StreamWriter.cs2
-rw-r--r--Emby.Server.Implementations/HttpServer/WebSocketConnection.cs9
-rw-r--r--Emby.Server.Implementations/IO/FileRefresher.cs23
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitor.cs28
-rw-r--r--Emby.Server.Implementations/IO/ManagedFileSystem.cs197
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Config.cs409
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs102
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs122
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs48
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs93
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs332
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs150
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs135
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs29
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs43
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs34
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs1161
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs43
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs29
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs29
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs34
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs35
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs30
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs28
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs28
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs28
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs28
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs55
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs43
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs616
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs579
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs41
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs49
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs734
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs305
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs32
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs27
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs285
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs148
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs65
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs202
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs269
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs52
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs68
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs660
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs448
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs920
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs164
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs59
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs140
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs63
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs54
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs156
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs197
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs140
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs249
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs438
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs677
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs287
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs25
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs221
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs80
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs389
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs67
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs64
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs37
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs33
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs29
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs122
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs157
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs95
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs94
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs202
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs88
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs78
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs93
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs40
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs206
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs807
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs28
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs900
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs101
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs692
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs257
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs36
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs47
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs62
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs57
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs63
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs57
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs56
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs52
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs193
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs116
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs70
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs164
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs93
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs63
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs190
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs87
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs57
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs95
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs107
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs87
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs75
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs234
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs92
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs346
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs206
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs226
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs84
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs52
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs106
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs150
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs50
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs50
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs302
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs212
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs3755
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs133
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs24
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs339
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs335
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs24
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs210
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs506
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs570
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs104
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs977
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs250
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs146
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs262
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs109
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs78
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs179
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs80
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs192
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs85
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs227
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs105
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs63
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs97
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs77
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs78
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs84
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs97
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs77
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs76
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs59
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs180
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs86
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs49
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs591
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs110
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs568
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs401
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs146
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs191
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs78
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs347
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs68
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs151
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs59
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs11
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs58
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs19
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs32
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs147
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs122
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs37
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs55
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs217
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs696
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs20
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs33
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs313
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs13
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs18
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs57
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs37
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs20
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs37
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs11
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs8
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs169
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs25
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs53
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs11
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs275
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs91
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs83
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs118
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs72
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs25
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs19
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs86
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs20
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs172
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs37
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs231
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs86
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs87
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs22
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs7
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs212
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs62
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs161
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs32
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs106
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs193
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs13
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs166
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs139
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs22
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs25
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs454
-rw-r--r--Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs63
-rw-r--r--Emby.Server.Implementations/IO/SharpCifsFileSystem.cs621
-rw-r--r--Emby.Server.Implementations/IO/StreamHelper.cs2
-rw-r--r--Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs2
-rw-r--r--Emby.Server.Implementations/Library/LibraryManager.cs81
-rw-r--r--Emby.Server.Implementations/Library/LiveStreamHelper.cs10
-rw-r--r--Emby.Server.Implementations/Library/MediaSourceManager.cs29
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs4
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs2
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs2
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs2
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs4
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs10
-rw-r--r--Emby.Server.Implementations/Library/SearchEngine.cs6
-rw-r--r--Emby.Server.Implementations/Library/UserDataManager.cs16
-rw-r--r--Emby.Server.Implementations/Library/UserManager.cs40
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs2
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs6
-rw-r--r--Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs2
-rw-r--r--Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs4
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs2
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresValidator.cs4
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs2
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs4
-rw-r--r--Emby.Server.Implementations/Library/Validators/PeopleValidator.cs12
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs2
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosValidator.cs6
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs12
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs143
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs35
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs6
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs2
-rw-r--r--Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs52
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs258
-rw-r--r--Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs303
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs11
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvManager.cs326
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs8
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs14
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs6
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs4
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs88
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs20
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs4
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs6
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs19
-rw-r--r--Emby.Server.Implementations/Localization/LocalizationManager.cs4
-rw-r--r--Emby.Server.Implementations/Logging/ConsoleLogger.cs13
-rw-r--r--Emby.Server.Implementations/Logging/SimpleLogManager.cs360
-rw-r--r--Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs45
-rw-r--r--Emby.Server.Implementations/MediaEncoder/EncodingManager.cs10
-rw-r--r--Emby.Server.Implementations/Net/SocketFactory.cs2
-rw-r--r--Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs106
-rw-r--r--Emby.Server.Implementations/Networking/NetworkManager.cs24
-rw-r--r--Emby.Server.Implementations/News/NewsEntryPoint.cs279
-rw-r--r--Emby.Server.Implementations/News/NewsService.cs77
-rw-r--r--Emby.Server.Implementations/Playlists/PlaylistManager.cs8
-rw-r--r--Emby.Server.Implementations/ResourceFileManager.cs4
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs8
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs4
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs2
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs36
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs2
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs2
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs128
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/TaskManager.cs27
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs10
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs6
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs110
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs2
-rw-r--r--Emby.Server.Implementations/Security/AuthenticationRepository.cs4
-rw-r--r--Emby.Server.Implementations/Security/PluginSecurityManager.cs19
-rw-r--r--Emby.Server.Implementations/Serialization/JsonSerializer.cs12
-rw-r--r--Emby.Server.Implementations/Serialization/XmlSerializer.cs6
-rw-r--r--Emby.Server.Implementations/ServerApplicationPaths.cs9
-rw-r--r--Emby.Server.Implementations/Services/ServiceController.cs10
-rw-r--r--Emby.Server.Implementations/Services/ServiceHandler.cs8
-rw-r--r--Emby.Server.Implementations/Services/ServicePath.cs16
-rw-r--r--Emby.Server.Implementations/Session/FirebaseSessionController.cs131
-rw-r--r--Emby.Server.Implementations/Session/SessionManager.cs77
-rw-r--r--Emby.Server.Implementations/Session/SessionWebSocketListener.cs10
-rw-r--r--Emby.Server.Implementations/Session/WebSocketController.cs2
-rw-r--r--Emby.Server.Implementations/StartupOptions.cs17
-rw-r--r--Emby.Server.Implementations/SystemEvents.cs3
-rw-r--r--Emby.Server.Implementations/TextEncoding/TextEncoding.cs8
-rw-r--r--Emby.Server.Implementations/Udp/UdpServer.cs17
-rw-r--r--Emby.Server.Implementations/Updates/InstallationManager.cs44
-rw-r--r--Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs10
-rw-r--r--Jellyfin.Server/CoreAppHost.cs57
-rw-r--r--Jellyfin.Server/Jellyfin.Server.csproj44
-rw-r--r--Jellyfin.Server/Program.cs313
-rw-r--r--Jellyfin.Server/Resources/Configuration/logging.json28
-rw-r--r--Jellyfin.Server/SocketSharp/HttpFile.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs)6
-rw-r--r--Jellyfin.Server/SocketSharp/RequestMono.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs)6
-rw-r--r--Jellyfin.Server/SocketSharp/SharpWebSocket.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs)11
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs)32
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs)6
-rw-r--r--Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs (renamed from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs)9
-rw-r--r--MediaBrowser.Api/ApiEntryPoint.cs42
-rw-r--r--MediaBrowser.Api/BaseApiService.cs5
-rw-r--r--MediaBrowser.Api/Images/ImageService.cs6
-rw-r--r--MediaBrowser.Api/ItemLookupService.cs5
-rw-r--r--MediaBrowser.Api/ItemRefreshService.cs2
-rw-r--r--MediaBrowser.Api/ItemUpdateService.cs2
-rw-r--r--MediaBrowser.Api/Library/LibraryService.cs3
-rw-r--r--MediaBrowser.Api/LiveTv/LiveTvService.cs1
-rw-r--r--MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs4
-rw-r--r--MediaBrowser.Api/MediaBrowser.Api.csproj2
-rw-r--r--MediaBrowser.Api/NewsService.cs46
-rw-r--r--MediaBrowser.Api/Playback/BaseStreamingService.cs33
-rw-r--r--MediaBrowser.Api/Playback/Hls/BaseHlsService.cs7
-rw-r--r--MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs19
-rw-r--r--MediaBrowser.Api/Playback/MediaInfoService.cs7
-rw-r--r--MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs2
-rw-r--r--MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs7
-rw-r--r--MediaBrowser.Api/Playback/StreamState.cs8
-rw-r--r--MediaBrowser.Api/Playback/TranscodingThrottler.cs24
-rw-r--r--MediaBrowser.Api/PluginService.cs6
-rw-r--r--MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs2
-rw-r--r--MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs2
-rw-r--r--MediaBrowser.Api/SimilarItemsHelper.cs2
-rw-r--r--MediaBrowser.Api/StartupWizardService.cs29
-rw-r--r--MediaBrowser.Api/Subtitles/SubtitleService.cs5
-rw-r--r--MediaBrowser.Api/System/ActivityLogWebSocketListener.cs2
-rw-r--r--MediaBrowser.Api/System/SystemService.cs10
-rw-r--r--MediaBrowser.Api/UserLibrary/PlaystateService.cs4
-rw-r--r--MediaBrowser.Api/UserLibrary/UserLibraryService.cs2
-rw-r--r--MediaBrowser.Api/UserService.cs5
-rw-r--r--MediaBrowser.Common/Events/EventHelper.cs52
-rw-r--r--MediaBrowser.Common/Extensions/BaseExtensions.cs20
-rw-r--r--MediaBrowser.Common/IApplicationHost.cs8
-rw-r--r--MediaBrowser.Common/MediaBrowser.Common.csproj2
-rw-r--r--MediaBrowser.Common/Net/IHttpClient.cs7
-rw-r--r--MediaBrowser.Common/Updates/GithubUpdater.cs278
-rw-r--r--MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs6
-rw-r--r--MediaBrowser.Controller/Chapters/IChapterManager.cs7
-rw-r--r--MediaBrowser.Controller/Collections/CollectionCreationOptions.cs4
-rw-r--r--MediaBrowser.Controller/Connect/IConnectManager.cs45
-rw-r--r--MediaBrowser.Controller/Dto/IDtoService.cs1
-rw-r--r--MediaBrowser.Controller/Entities/AggregateFolder.cs2
-rw-r--r--MediaBrowser.Controller/Entities/Audio/Audio.cs9
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs4
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicArtist.cs11
-rw-r--r--MediaBrowser.Controller/Entities/Audio/MusicGenre.cs5
-rw-r--r--MediaBrowser.Controller/Entities/BaseItem.cs63
-rw-r--r--MediaBrowser.Controller/Entities/CollectionFolder.cs26
-rw-r--r--MediaBrowser.Controller/Entities/Folder.cs60
-rw-r--r--MediaBrowser.Controller/Entities/Game.cs19
-rw-r--r--MediaBrowser.Controller/Entities/GameGenre.cs5
-rw-r--r--MediaBrowser.Controller/Entities/Genre.cs5
-rw-r--r--MediaBrowser.Controller/Entities/InternalItemsQuery.cs66
-rw-r--r--MediaBrowser.Controller/Entities/InternalPeopleQuery.cs4
-rw-r--r--MediaBrowser.Controller/Entities/Movies/BoxSet.cs19
-rw-r--r--MediaBrowser.Controller/Entities/Movies/Movie.cs9
-rw-r--r--MediaBrowser.Controller/Entities/MusicVideo.cs2
-rw-r--r--MediaBrowser.Controller/Entities/Person.cs5
-rw-r--r--MediaBrowser.Controller/Entities/Photo.cs5
-rw-r--r--MediaBrowser.Controller/Entities/Studio.cs5
-rw-r--r--MediaBrowser.Controller/Entities/TV/Episode.cs15
-rw-r--r--MediaBrowser.Controller/Entities/TV/Season.cs7
-rw-r--r--MediaBrowser.Controller/Entities/TV/Series.cs8
-rw-r--r--MediaBrowser.Controller/Entities/Trailer.cs9
-rw-r--r--MediaBrowser.Controller/Entities/UserView.cs19
-rw-r--r--MediaBrowser.Controller/Entities/UserViewBuilder.cs12
-rw-r--r--MediaBrowser.Controller/Entities/Video.cs28
-rw-r--r--MediaBrowser.Controller/Entities/Year.cs3
-rw-r--r--MediaBrowser.Controller/IO/FileData.cs6
-rw-r--r--MediaBrowser.Controller/IResourceFileManager.cs2
-rw-r--r--MediaBrowser.Controller/IServerApplicationHost.cs6
-rw-r--r--MediaBrowser.Controller/Library/IUserDataManager.cs1
-rw-r--r--MediaBrowser.Controller/Library/ItemResolveArgs.cs8
-rw-r--r--MediaBrowser.Controller/Library/Profiler.cs4
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvProgram.cs43
-rw-r--r--MediaBrowser.Controller/LiveTv/TimerInfo.cs4
-rw-r--r--MediaBrowser.Controller/MediaBrowser.Controller.csproj2
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs33
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs15
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs4
-rw-r--r--MediaBrowser.Controller/MediaEncoding/JobLogger.cs4
-rw-r--r--MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs2
-rw-r--r--MediaBrowser.Controller/Net/AuthorizationInfo.cs8
-rw-r--r--MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs10
-rw-r--r--MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs2
-rw-r--r--MediaBrowser.Controller/Playlists/IPlaylistManager.cs1
-rw-r--r--MediaBrowser.Controller/Playlists/Playlist.cs29
-rw-r--r--MediaBrowser.Controller/Providers/AlbumInfo.cs4
-rw-r--r--MediaBrowser.Controller/Providers/DirectoryService.cs12
-rw-r--r--MediaBrowser.Controller/Providers/ImageRefreshOptions.cs4
-rw-r--r--MediaBrowser.Controller/Providers/ItemLookupInfo.cs2
-rw-r--r--MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs11
-rw-r--r--MediaBrowser.Controller/Providers/MetadataResult.cs2
-rw-r--r--MediaBrowser.Controller/Providers/SongInfo.cs7
-rw-r--r--MediaBrowser.Controller/Session/AuthenticationRequest.cs2
-rw-r--r--MediaBrowser.Controller/Session/ISessionManager.cs1
-rw-r--r--MediaBrowser.Controller/Session/SessionInfo.cs22
-rw-r--r--MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs6
-rw-r--r--MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs6
-rw-r--r--MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj2
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs4
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs4
-rw-r--r--MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs2
-rw-r--r--MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs18
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs122
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs59
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs182
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs102
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs4
-rw-r--r--MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj2
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs17
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs18
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs4
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs212
-rw-r--r--MediaBrowser.Model/Activity/ActivityLogEntry.cs4
-rw-r--r--MediaBrowser.Model/Channels/ChannelFeatures.cs9
-rw-r--r--MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs8
-rw-r--r--MediaBrowser.Model/Configuration/LibraryOptions.cs21
-rw-r--r--MediaBrowser.Model/Configuration/MetadataOptions.cs21
-rw-r--r--MediaBrowser.Model/Configuration/MetadataPluginSummary.cs8
-rw-r--r--MediaBrowser.Model/Configuration/ServerConfiguration.cs51
-rw-r--r--MediaBrowser.Model/Configuration/UserConfiguration.cs8
-rw-r--r--MediaBrowser.Model/Connect/ConnectAuthenticationExchangeResult.cs17
-rw-r--r--MediaBrowser.Model/Connect/ConnectAuthenticationResult.cs17
-rw-r--r--MediaBrowser.Model/Connect/ConnectAuthorization.cs4
-rw-r--r--MediaBrowser.Model/Connect/ConnectAuthorizationRequest.cs19
-rw-r--r--MediaBrowser.Model/Devices/DeviceInfo.cs16
-rw-r--r--MediaBrowser.Model/Devices/DeviceQuery.cs9
-rw-r--r--MediaBrowser.Model/Devices/DevicesOptions.cs5
-rw-r--r--MediaBrowser.Model/Dlna/ContainerProfile.cs8
-rw-r--r--MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs3
-rw-r--r--MediaBrowser.Model/Dlna/ResolutionNormalizer.cs37
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs14
-rw-r--r--MediaBrowser.Model/Dlna/StreamInfo.cs8
-rw-r--r--MediaBrowser.Model/Dlna/SubtitleProfile.cs4
-rw-r--r--MediaBrowser.Model/Dto/BaseItemDto.cs35
-rw-r--r--MediaBrowser.Model/Dto/ChapterInfoDto.cs38
-rw-r--r--MediaBrowser.Model/Dto/GameSystemSummary.cs5
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceInfo.cs9
-rw-r--r--MediaBrowser.Model/Dto/MetadataEditorInfo.cs12
-rw-r--r--MediaBrowser.Model/Dto/UserDto.cs1
-rw-r--r--MediaBrowser.Model/Entities/LibraryUpdateInfo.cs12
-rw-r--r--MediaBrowser.Model/Entities/VirtualFolderInfo.cs2
-rw-r--r--MediaBrowser.Model/Globalization/CultureDto.cs2
-rw-r--r--MediaBrowser.Model/Library/UserViewQuery.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvInfo.cs6
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvOptions.cs18
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/ProgramQuery.cs117
-rw-r--r--MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs73
-rw-r--r--MediaBrowser.Model/Logging/IConsoleLogger.cs7
-rw-r--r--MediaBrowser.Model/Logging/ILogManager.cs56
-rw-r--r--MediaBrowser.Model/Logging/ILogger.cs78
-rw-r--r--MediaBrowser.Model/Logging/LogHelper.cs97
-rw-r--r--MediaBrowser.Model/Logging/LogSeverity.cs30
-rw-r--r--MediaBrowser.Model/Logging/NullLogger.cs44
-rw-r--r--MediaBrowser.Model/MediaBrowser.Model.csproj6
-rw-r--r--MediaBrowser.Model/MediaInfo/MediaInfo.cs16
-rw-r--r--MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs1
-rw-r--r--MediaBrowser.Model/News/INewsService.cs17
-rw-r--r--MediaBrowser.Model/News/NewsItem.cs14
-rw-r--r--MediaBrowser.Model/News/NewsQuery.cs9
-rw-r--r--MediaBrowser.Model/Notifications/NotificationOption.cs20
-rw-r--r--MediaBrowser.Model/Notifications/NotificationRequest.cs3
-rw-r--r--MediaBrowser.Model/Notifications/NotificationServiceInfo.cs8
-rw-r--r--MediaBrowser.Model/Notifications/NotificationTypeInfo.cs16
-rw-r--r--MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs5
-rw-r--r--MediaBrowser.Model/Providers/SubtitleOptions.cs4
-rw-r--r--MediaBrowser.Model/Querying/QueryFilters.cs12
-rw-r--r--MediaBrowser.Model/Search/SearchQuery.cs6
-rw-r--r--MediaBrowser.Model/Session/ClientCapabilities.cs8
-rw-r--r--MediaBrowser.Model/Session/SessionInfoDto.cs117
-rw-r--r--MediaBrowser.Model/Sync/SyncJob.cs4
-rw-r--r--MediaBrowser.Model/System/Architecture.cs10
-rw-r--r--MediaBrowser.Model/System/IEnvironmentInfo.cs3
-rw-r--r--MediaBrowser.Model/System/IPowerManagement.cs11
-rw-r--r--MediaBrowser.Model/System/SystemInfo.cs9
-rw-r--r--MediaBrowser.Model/Tasks/ITaskTrigger.cs4
-rw-r--r--MediaBrowser.Model/Users/UserPolicy.cs16
-rw-r--r--MediaBrowser.Providers/Books/AudioBookMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Books/BookMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs2
-rw-r--r--MediaBrowser.Providers/Channels/ChannelMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Chapters/ChapterManager.cs13
-rw-r--r--MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Folders/FolderMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Folders/UserViewMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Games/GameMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Games/GameSystemMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Genres/GenreMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Manager/ImageSaver.cs12
-rw-r--r--MediaBrowser.Providers/Manager/ItemImageProvider.cs18
-rw-r--r--MediaBrowser.Providers/Manager/MetadataService.cs30
-rw-r--r--MediaBrowser.Providers/Manager/ProviderManager.cs76
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs6
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs10
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs4
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs4
-rw-r--r--MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs4
-rw-r--r--MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs2
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbProvider.cs13
-rw-r--r--MediaBrowser.Providers/Movies/MovieDbSearch.cs4
-rw-r--r--MediaBrowser.Providers/Movies/MovieMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Music/AlbumMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Music/ArtistMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Music/AudioMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs88
-rw-r--r--MediaBrowser.Providers/Music/MusicVideoMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Omdb/OmdbItemProvider.cs2
-rw-r--r--MediaBrowser.Providers/Omdb/OmdbProvider.cs16
-rw-r--r--MediaBrowser.Providers/People/MovieDbPersonProvider.cs2
-rw-r--r--MediaBrowser.Providers/People/PersonMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Photos/PhotoMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs4
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Studios/StudioMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Subtitles/SubtitleManager.cs16
-rw-r--r--MediaBrowser.Providers/TV/DummySeasonProvider.cs8
-rw-r--r--MediaBrowser.Providers/TV/EpisodeMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/TV/MissingEpisodeProvider.cs8
-rw-r--r--MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs2
-rw-r--r--MediaBrowser.Providers/TV/SeasonMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/TV/SeriesMetadataService.cs4
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs6
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs6
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs6
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs8
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs4
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs4
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs6
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs2
-rw-r--r--MediaBrowser.Providers/Users/UserMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Videos/VideoMetadataService.cs2
-rw-r--r--MediaBrowser.Providers/Years/YearMetadataService.cs2
-rw-r--r--MediaBrowser.Server.Mono/EmbyServer.csproj55
-rw-r--r--MediaBrowser.Server.Mono/ImageEncoderHelper.cs51
-rw-r--r--MediaBrowser.Server.Mono/MonoAppHost.cs102
-rw-r--r--MediaBrowser.Server.Mono/Native/MonoFileSystem.cs23
-rw-r--r--MediaBrowser.Server.Mono/Native/PowerManagement.cs21
-rw-r--r--MediaBrowser.Server.Mono/Program.cs326
-rw-r--r--MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs15
-rw-r--r--MediaBrowser.Server.Mono/Properties/launchSettings.json7
-rw-r--r--MediaBrowser.Tests/M3uParserTest.cs2
-rw-r--r--MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs4
-rw-r--r--MediaBrowser.WebDashboard/Api/DashboardService.cs4
-rw-r--r--MediaBrowser.WebDashboard/Api/PackageCreator.cs2
-rw-r--r--MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj2
-rw-r--r--MediaBrowser.XbmcMetadata/EntryPoint.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj2
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs14
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs15
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs4
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs2
-rw-r--r--MediaBrowser.sln447
-rw-r--r--Mono.Nat/Mono.Nat.csproj2
-rw-r--r--Mono.Nat/NatManager.cs2
-rw-r--r--Mono.Nat/Pmp/PmpNatDevice.cs8
-rw-r--r--Mono.Nat/Pmp/PmpSearcher.cs4
-rw-r--r--Mono.Nat/Upnp/Messages/GetServicesMessage.cs6
-rw-r--r--Mono.Nat/Upnp/Searchers/UpnpSearcher.cs4
-rw-r--r--Mono.Nat/Upnp/UpnpNatDevice.cs22
-rw-r--r--README.md49
-rw-r--r--RSSDP/LICENSE4
-rw-r--r--RSSDP/SsdpCommunicationsServer.cs16
-rw-r--r--SharedVersion.cs2
-rw-r--r--SocketHttpListener/Net/HttpConnection.cs6
-rw-r--r--SocketHttpListener/Net/HttpEndPointListener.cs12
-rw-r--r--SocketHttpListener/Net/HttpEndPointManager.cs2
-rw-r--r--SocketHttpListener/Net/HttpListener.cs7
-rw-r--r--SocketHttpListener/Net/HttpListenerContext.cs4
-rw-r--r--SocketHttpListener/Net/HttpListenerPrefixCollection.cs2
-rw-r--r--SocketHttpListener/Net/HttpResponseStream.Managed.cs2
-rw-r--r--SocketHttpListener/SocketHttpListener.csproj2
-rw-r--r--build-jellyfin.ps12
-rw-r--r--debian/changelog23
-rw-r--r--debian/conf/jellyfin8
-rw-r--r--debian/conf/logging.json29
-rw-r--r--debian/control3
-rw-r--r--debian/install1
-rw-r--r--debian/jellyfin.service2
-rw-r--r--debian/postinst29
-rw-r--r--debian/postrm29
-rw-r--r--debian/preinst20
-rw-r--r--debian/prerm12
-rw-r--r--debian/source/options1
747 files changed, 3810 insertions, 48314 deletions
diff --git a/.dockerignore b/.dockerignore
index 6b8710a71..fc4d8ed26 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1 +1,5 @@
.git
+.dockerignore
+Dockerfile
+CONTRIBUTORS.md
+README.md
diff --git a/.drone.yml b/.drone.yml
index 13762ba0a..c6d41b555 100644
--- a/.drone.yml
+++ b/.drone.yml
@@ -1,32 +1,12 @@
kind: pipeline
-name: build:debian
+name: build
steps:
- name: submodules
image: docker:git
commands:
- git submodule update --init --recursive
-- name: build:debian
- image: plugins/docker
- group: build
- settings:
- repo: jellyfin/jellyfin
- dry_run: true
- dockerfile: Dockerfile.debian_package
-
-
----
-kind: pipeline
-name: build:docker
-
-steps:
-- name: submodules
- image: docker:git
+- name: build
+ image: microsoft/dotnet:2-sdk
commands:
- - git submodule update --init --recursive
-- name: build:docker
- image: plugins/docker
- group: build
- settings:
- repo: jellyfin/jellyfin
- dry_run: true
+ - dotnet publish --configuration release --output /release
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 000000000..a3b72c9af
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,133 @@
+# With more recent updates Visual Studio 2017 supports EditorConfig files out of the box
+# Visual Studio Code needs an extension: https://github.com/editorconfig/editorconfig-vscode
+# For emacs, vim, np++ and other editors, see here: https://github.com/editorconfig
+###############################
+# Core EditorConfig Options #
+###############################
+# All files
+[*]
+indent_style = space
+root = true
+indent_size = 4
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+end_of_line = lf
+max_line_length = null
+
+# Code files
+[*.{cs,csx,vb,vbx}]
+indent_size = 4
+insert_final_newline = true
+charset = utf-8
+###############################
+# .NET Coding Conventions #
+###############################
+[*.{cs,vb}]
+# Organize usings
+dotnet_sort_system_directives_first = true
+# this. preferences
+dotnet_style_qualification_for_field = false:silent
+dotnet_style_qualification_for_property = false:silent
+dotnet_style_qualification_for_method = false:silent
+dotnet_style_qualification_for_event = false:silent
+# Language keywords vs BCL types preferences
+dotnet_style_predefined_type_for_locals_parameters_members = true:silent
+dotnet_style_predefined_type_for_member_access = true:silent
+# Parentheses preferences
+dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
+dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
+# Modifier preferences
+dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
+dotnet_style_readonly_field = true:suggestion
+# Expression-level preferences
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
+dotnet_prefer_inferred_tuple_names = true:suggestion
+dotnet_prefer_inferred_anonymous_type_member_names = true:suggestion
+dotnet_style_prefer_auto_properties = true:silent
+dotnet_style_prefer_conditional_expression_over_assignment = true:silent
+dotnet_style_prefer_conditional_expression_over_return = true:silent
+###############################
+# Naming Conventions #
+###############################
+# Style Definitions
+dotnet_naming_style.pascal_case_style.capitalization = pascal_case
+# Use PascalCase for constant fields
+dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
+dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
+dotnet_naming_symbols.constant_fields.applicable_kinds = field
+dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
+dotnet_naming_symbols.constant_fields.required_modifiers = const
+###############################
+# C# Coding Conventions #
+###############################
+[*.cs]
+# var preferences
+csharp_style_var_for_built_in_types = true:silent
+csharp_style_var_when_type_is_apparent = true:silent
+csharp_style_var_elsewhere = true:silent
+# Expression-bodied members
+csharp_style_expression_bodied_methods = false:silent
+csharp_style_expression_bodied_constructors = false:silent
+csharp_style_expression_bodied_operators = false:silent
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
+# Pattern matching preferences
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
+# Null-checking preferences
+csharp_style_throw_expression = true:suggestion
+csharp_style_conditional_delegate_call = true:suggestion
+# Modifier preferences
+csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
+# Expression-level preferences
+csharp_prefer_braces = true:silent
+csharp_style_deconstructed_variable_declaration = true:suggestion
+csharp_prefer_simple_default_expression = true:suggestion
+csharp_style_pattern_local_over_anonymous_function = true:suggestion
+csharp_style_inlined_variable_declaration = true:suggestion
+###############################
+# C# Formatting Rules #
+###############################
+# New line preferences
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_between_query_expression_clauses = true
+# Indentation preferences
+csharp_indent_case_contents = true
+csharp_indent_switch_labels = true
+csharp_indent_labels = flush_left
+# Space preferences
+csharp_space_after_cast = false
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_between_method_call_parameter_list_parentheses = false
+csharp_space_between_method_declaration_parameter_list_parentheses = false
+csharp_space_between_parentheses = false
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+# Wrapping preferences
+csharp_preserve_single_line_statements = true
+csharp_preserve_single_line_blocks = true
+###############################
+# VB Coding Conventions #
+###############################
+[*.vb]
+# Modifier preferences
+visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion
diff --git a/.gitignore b/.gitignore
index ff9e52259..befba5a20 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
!*
+.directory
+
#################
## Eclipse
#################
@@ -245,6 +247,8 @@ MediaBrowser.WebDashboard/dashboard-ui/.idea/
#########################
debian/.debhelper/
+debian/*.debhelper
+debian/debhelper-build-stamp
debian/files
debian/jellyfin.substvars
debian/jellyfin/
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 000000000..21b8323ea
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,28 @@
+{
+ // Use IntelliSense to find out which attributes exist for C# debugging
+ // Use hover for the description of the existing attributes
+ // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": ".NET Core Launch (console)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ // If you have changed target frameworks, make sure to update the program path.
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll",
+ "args": [],
+ "cwd": "${workspaceFolder}/Jellyfin.Server",
+ // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
+ "console": "internalConsole",
+ "stopAtEntry": false,
+ "internalConsoleOptions": "openOnSessionStart"
+ },
+ {
+ "name": ".NET Core Attach",
+ "type": "coreclr",
+ "request": "attach",
+ "processId": "${command:pickProcess}"
+ }
+ ,]
+} \ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 000000000..ac517e10c
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,15 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "build",
+ "command": "dotnet",
+ "type": "process",
+ "args": [
+ "build",
+ "${workspaceFolder}/Jellyfin.Server/Jellyfin.Server.csproj"
+ ],
+ "problemMatcher": "$msCompile"
+ }
+ ]
+} \ No newline at end of file
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 467ba1522..6517b63cd 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -7,15 +7,19 @@
- [EraYaN](https://github.com/EraYaN)
- [flemse](https://github.com/flemse)
- [bfayers](https://github.com/bfayers)
+ - [Bond_009](https://github.com/Bond-009)
+ - [AnthonyLavado](https://github.com/anthonylavado)
+ - [sparky8251](https://github.com/sparky8251)
+ - [LeoVerto](https://github.com/LeoVerto]
# Emby Contributors
- - [LukePulverenti](https://github.com/LukePulverenti)
- - [ebr11](https://github.com/ebr11)
- - [lalmanzar](https://github.com/lalmanzar)
- - [schneifu](https://github.com/schneifu)
- - [Mark2xv](https://github.com/Mark2xv)
- - [ScottRapsey](https://github.com/ScottRapsey)
+ - [LukePulverenti](https://github.com/LukePulverenti)
+ - [ebr11](https://github.com/ebr11)
+ - [lalmanzar](https://github.com/lalmanzar)
+ - [schneifu](https://github.com/schneifu)
+ - [Mark2xv](https://github.com/Mark2xv)
+ - [ScottRapsey](https://github.com/ScottRapsey)
- [skynet600](https://github.com/skynet600)
- [Cheesegeezer](https://githum.com/Cheesegeezer)
- [Radeon](https://github.com/radeonorama)
diff --git a/Dockerfile b/Dockerfile
index f5e345225..75700e6f5 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,5 +1,15 @@
ARG DOTNET_VERSION=2
+
+# Download ffmpeg first to allow quicker rebuild of other layers
+FROM alpine as ffmpeg
+ARG FFMPEG_URL=https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz
+RUN wget ${FFMPEG_URL} -O - | tar Jxf - \
+ && mkdir ffmpeg-bin \
+ && mv ffmpeg*/ffmpeg ffmpeg-bin \
+ && mv ffmpeg*/ffprobe ffmpeg-bin
+
+
FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder
WORKDIR /repo
COPY . .
@@ -7,12 +17,12 @@ RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \
&& dotnet clean \
&& dotnet publish --configuration release --output /jellyfin
+
FROM microsoft/dotnet:${DOTNET_VERSION}-runtime
COPY --from=builder /jellyfin /jellyfin
+COPY --from=ffmpeg /ffmpeg-bin/* /usr/bin/
EXPOSE 8096
-RUN apt update \
- && apt install -y ffmpeg
VOLUME /config /media
-ENTRYPOINT if [ -n "$PUID$PGUID" ]; \
- then echo "PUID/PGID are deprecated. Use Docker user param." >&2; exit 1; \
- else dotnet /jellyfin/jellyfin.dll -programdata /config; fi
+RUN apt update \
+ && apt install -y libfontconfig1 # needed for Skia
+ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config
diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs
index 3f33f3ebf..ab747d189 100644
--- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs
+++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs
@@ -2,9 +2,9 @@
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
using Emby.Dlna.Service;
-using MediaBrowser.Model.Logging;
using System.Collections.Generic;
using MediaBrowser.Model.Xml;
+using Microsoft.Extensions.Logging;
namespace Emby.Dlna.ConnectionManager
{
diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs
index ae983c5e7..7e3e5f650 100644
--- a/Emby.Dlna/ConnectionManager/ControlHandler.cs
+++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration;
using Emby.Dlna.Server;
using Emby.Dlna.Service;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Xml;
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs
index 0aabe099c..7c809a952 100644
--- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs
+++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using Emby.Dlna.Service;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.MediaEncoding;
diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs
index bf9c48ac7..57d4078a5 100644
--- a/Emby.Dlna/ContentDirectory/ControlHandler.cs
+++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs
@@ -12,7 +12,7 @@ using Emby.Dlna.Service;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
@@ -68,7 +68,7 @@ namespace Emby.Dlna.ContentDirectory
_profile = profile;
_config = config;
- _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, libraryManager, mediaEncoder);
+ _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, libraryManager, mediaEncoder);
}
protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams)
@@ -1334,7 +1334,7 @@ namespace Emby.Dlna.ContentDirectory
};
}
- Logger.Error("Error parsing item Id: {0}. Returning user root folder.", id);
+ _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id);
return new ServerItem(_libraryManager.GetUserRootFolder());
}
diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs
index 8d59ea3ff..7af48ae17 100644
--- a/Emby.Dlna/Didl/DidlBuilder.cs
+++ b/Emby.Dlna/Didl/DidlBuilder.cs
@@ -11,7 +11,7 @@ using Emby.Dlna.ContentDirectory;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using System;
using System.Globalization;
@@ -173,16 +173,6 @@ namespace Emby.Dlna.Didl
writer.WriteFullEndElement();
}
- private ILogger GetStreamBuilderLogger(DlnaOptions options)
- {
- if (options.EnableDebugLog)
- {
- return _logger;
- }
-
- return new NullLogger();
- }
-
private string GetMimeType(string input)
{
var mime = MimeTypes.GetMimeType(input);
@@ -202,7 +192,7 @@ namespace Emby.Dlna.Didl
{
var sources = _mediaSourceManager.GetStaticMediaSources(video, true, _user);
- streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildVideoItem(new VideoOptions
+ streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions
{
ItemId = video.Id,
MediaSources = sources.ToArray(),
@@ -509,7 +499,7 @@ namespace Emby.Dlna.Didl
{
var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user);
- streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildAudioItem(new AudioOptions
+ streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions
{
ItemId = audio.Id,
MediaSources = sources.ToArray(),
@@ -923,9 +913,9 @@ namespace Emby.Dlna.Didl
writer.WriteFullEndElement();
}
- catch (XmlException)
+ catch (XmlException ex)
{
- //_logger.Error("Error adding xml value: " + value);
+ _logger.LogError(ex, "Error adding xml value: {value}", name);
}
}
@@ -935,9 +925,9 @@ namespace Emby.Dlna.Didl
{
writer.WriteElementString(prefix, name, namespaceUri, value);
}
- catch (XmlException)
+ catch (XmlException ex)
{
- //_logger.Error("Error adding xml value: " + value);
+ _logger.LogError(ex, "Error adding xml value: {value}", value);
}
}
@@ -1080,9 +1070,9 @@ namespace Emby.Dlna.Didl
{
tag = _imageProcessor.GetImageCacheTag(item, type);
}
- catch
+ catch (Exception ex)
{
-
+ _logger.LogError(ex, "Error getting image cache tag");
}
int? width = imageInfo.Width;
diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs
index 62d1eb57c..48a33757b 100644
--- a/Emby.Dlna/DlnaManager.cs
+++ b/Emby.Dlna/DlnaManager.cs
@@ -8,7 +8,7 @@ using Emby.Dlna.Profiles;
using Emby.Dlna.Server;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
@@ -58,7 +58,7 @@ namespace Emby.Dlna
}
catch (Exception ex)
{
- _logger.ErrorException("Error extracting DLNA profiles.", ex);
+ _logger.LogError(ex, "Error extracting DLNA profiles.");
}
}
@@ -103,7 +103,7 @@ namespace Emby.Dlna
if (profile != null)
{
- _logger.Debug("Found matching device profile: {0}", profile.Name);
+ _logger.LogDebug("Found matching device profile: {0}", profile.Name);
}
else
{
@@ -117,6 +117,7 @@ namespace Emby.Dlna
{
var builder = new StringBuilder();
+ builder.AppendLine("No matching device profile found. The default will need to be used.");
builder.AppendLine(string.Format("DeviceDescription:{0}", profile.DeviceDescription ?? string.Empty));
builder.AppendLine(string.Format("FriendlyName:{0}", profile.FriendlyName ?? string.Empty));
builder.AppendLine(string.Format("Manufacturer:{0}", profile.Manufacturer ?? string.Empty));
@@ -127,7 +128,7 @@ namespace Emby.Dlna
builder.AppendLine(string.Format("ModelUrl:{0}", profile.ModelUrl ?? string.Empty));
builder.AppendLine(string.Format("SerialNumber:{0}", profile.SerialNumber ?? string.Empty));
- _logger.LogMultiline("No matching device profile found. The default will need to be used.", LogSeverity.Info, builder);
+ _logger.LogInformation(builder.ToString());
}
private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo)
@@ -197,7 +198,7 @@ namespace Emby.Dlna
}
catch (ArgumentException ex)
{
- _logger.ErrorException("Error evaluating regex pattern {0}", ex, pattern);
+ _logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern);
return false;
}
}
@@ -216,12 +217,12 @@ namespace Emby.Dlna
if (profile != null)
{
- _logger.Debug("Found matching device profile: {0}", profile.Name);
+ _logger.LogDebug("Found matching device profile: {0}", profile.Name);
}
else
{
var headerString = string.Join(", ", headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
- _logger.Debug("No matching device profile found. {0}", headerString);
+ _logger.LogDebug("No matching device profile found. {0}", headerString);
}
return profile;
@@ -250,7 +251,7 @@ namespace Emby.Dlna
return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
case HeaderMatchType.Substring:
var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
- //_logger.Debug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
+ //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
return isMatch;
case HeaderMatchType.Regex:
return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase);
@@ -323,7 +324,7 @@ namespace Emby.Dlna
}
catch (Exception ex)
{
- _logger.ErrorException("Error parsing profile file: {0}", ex, path);
+ _logger.LogError(ex, "Error parsing profile file: {Path}", path);
return null;
}
@@ -530,8 +531,8 @@ namespace Emby.Dlna
};
}
}
-
- class DlnaProfileEntryPoint /*: IServerEntryPoint*/
+ /*
+ class DlnaProfileEntryPoint : IServerEntryPoint
{
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
@@ -551,7 +552,7 @@ namespace Emby.Dlna
private void DumpProfiles()
{
- var list = new List<DeviceProfile>
+ DeviceProfile[] list = new []
{
new SamsungSmartTvProfile(),
new XboxOneProfile(),
@@ -596,5 +597,5 @@ namespace Emby.Dlna
public void Dispose()
{
}
- }
-} \ No newline at end of file
+ }*/
+}
diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs
index 0638cff89..ea9ba3f22 100644
--- a/Emby.Dlna/Eventing/EventManager.cs
+++ b/Emby.Dlna/Eventing/EventManager.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -34,7 +34,7 @@ namespace Emby.Dlna.Eventing
// Remove logging for now because some devices are sending this very frequently
// TODO re-enable with dlna debug logging setting
- //_logger.Debug("Renewing event subscription for {0} with timeout of {1} to {2}",
+ //_logger.LogDebug("Renewing event subscription for {0} with timeout of {1} to {2}",
// subscription.NotificationType,
// timeout,
// subscription.CallbackUrl);
@@ -60,7 +60,7 @@ namespace Emby.Dlna.Eventing
// Remove logging for now because some devices are sending this very frequently
// TODO re-enable with dlna debug logging setting
- //_logger.Debug("Creating event subscription for {0} with timeout of {1} to {2}",
+ //_logger.LogDebug("Creating event subscription for {0} with timeout of {1} to {2}",
// notificationType,
// timeout,
// callbackUrl);
@@ -96,7 +96,7 @@ namespace Emby.Dlna.Eventing
public EventSubscriptionResponse CancelEventSubscription(string subscriptionId)
{
- _logger.Debug("Cancelling event subscription {0}", subscriptionId);
+ _logger.LogDebug("Cancelling event subscription {0}", subscriptionId);
EventSubscription sub;
_subscriptions.TryRemove(subscriptionId, out sub);
diff --git a/Emby.Dlna/Images/logo120.jpg b/Emby.Dlna/Images/logo120.jpg
index 9a0e199a3..c70f4db0d 100644
--- a/Emby.Dlna/Images/logo120.jpg
+++ b/Emby.Dlna/Images/logo120.jpg
Binary files differ
diff --git a/Emby.Dlna/Images/logo120.png b/Emby.Dlna/Images/logo120.png
index c7fc5c1ce..321c47729 100644
--- a/Emby.Dlna/Images/logo120.png
+++ b/Emby.Dlna/Images/logo120.png
Binary files differ
diff --git a/Emby.Dlna/Images/logo240.jpg b/Emby.Dlna/Images/logo240.jpg
index 74cb2c429..da1cb5e07 100644
--- a/Emby.Dlna/Images/logo240.jpg
+++ b/Emby.Dlna/Images/logo240.jpg
Binary files differ
diff --git a/Emby.Dlna/Images/logo240.png b/Emby.Dlna/Images/logo240.png
index d229ed24c..64c828129 100644
--- a/Emby.Dlna/Images/logo240.png
+++ b/Emby.Dlna/Images/logo240.png
Binary files differ
diff --git a/Emby.Dlna/Images/logo48.jpg b/Emby.Dlna/Images/logo48.jpg
index 9822a8e2f..269bcf589 100644
--- a/Emby.Dlna/Images/logo48.jpg
+++ b/Emby.Dlna/Images/logo48.jpg
Binary files differ
diff --git a/Emby.Dlna/Images/logo48.png b/Emby.Dlna/Images/logo48.png
index 23007e155..b8fc14564 100644
--- a/Emby.Dlna/Images/logo48.png
+++ b/Emby.Dlna/Images/logo48.png
Binary files differ
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index cd535a98a..6ab0767a5 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -11,7 +11,7 @@ using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.TV;
using Emby.Dlna.PlayTo;
using Emby.Dlna.Ssdp;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
@@ -64,7 +64,7 @@ namespace Emby.Dlna.Main
public static DlnaEntryPoint Current;
public DlnaEntryPoint(IServerConfigurationManager config,
- ILogManager logManager,
+ ILoggerFactory loggerFactory,
IServerApplicationHost appHost,
ISessionManager sessionManager,
IHttpClient httpClient,
@@ -102,7 +102,7 @@ namespace Emby.Dlna.Main
_timerFactory = timerFactory;
_environmentInfo = environmentInfo;
_networkManager = networkManager;
- _logger = logManager.GetLogger("Dlna");
+ _logger = loggerFactory.CreateLogger("Dlna");
ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager,
userDataManager,
@@ -185,13 +185,13 @@ namespace Emby.Dlna.Main
}
catch (Exception ex)
{
- _logger.ErrorException("Error starting ssdp handlers", ex);
+ _logger.LogError(ex, "Error starting ssdp handlers");
}
}
private void LogMessage(string msg)
{
- _logger.Debug(msg);
+ _logger.LogDebug(msg);
}
private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer)
@@ -202,7 +202,7 @@ namespace Emby.Dlna.Main
}
catch (Exception ex)
{
- _logger.ErrorException("Error starting device discovery", ex);
+ _logger.LogError(ex, "Error starting device discovery");
}
}
@@ -210,12 +210,12 @@ namespace Emby.Dlna.Main
{
try
{
- _logger.Info("Disposing DeviceDiscovery");
+ _logger.LogInformation("Disposing DeviceDiscovery");
((DeviceDiscovery)_deviceDiscovery).Dispose();
}
catch (Exception ex)
{
- _logger.ErrorException("Error stopping device discovery", ex);
+ _logger.LogError(ex, "Error stopping device discovery");
}
}
@@ -243,7 +243,7 @@ namespace Emby.Dlna.Main
}
catch (Exception ex)
{
- _logger.ErrorException("Error registering endpoint", ex);
+ _logger.LogError(ex, "Error registering endpoint");
}
}
@@ -263,7 +263,7 @@ namespace Emby.Dlna.Main
var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
- _logger.Info("Registering publisher for {0} on {1}", fullService, address.ToString());
+ _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address.ToString());
var descriptorUri = "/dlna/" + udn + "/description.xml";
var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);
@@ -361,7 +361,7 @@ namespace Emby.Dlna.Main
}
catch (Exception ex)
{
- _logger.ErrorException("Error starting PlayTo manager", ex);
+ _logger.LogError(ex, "Error starting PlayTo manager");
}
}
}
@@ -374,12 +374,12 @@ namespace Emby.Dlna.Main
{
try
{
- _logger.Info("Disposing PlayToManager");
+ _logger.LogInformation("Disposing PlayToManager");
_manager.Dispose();
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing PlayTo manager", ex);
+ _logger.LogError(ex, "Error disposing PlayTo manager");
}
_manager = null;
}
@@ -394,7 +394,7 @@ namespace Emby.Dlna.Main
if (_communicationsServer != null)
{
- _logger.Info("Disposing SsdpCommunicationsServer");
+ _logger.LogInformation("Disposing SsdpCommunicationsServer");
_communicationsServer.Dispose();
_communicationsServer = null;
}
@@ -409,7 +409,7 @@ namespace Emby.Dlna.Main
{
if (_Publisher != null)
{
- _logger.Info("Disposing SsdpDevicePublisher");
+ _logger.LogInformation("Disposing SsdpDevicePublisher");
_Publisher.Dispose();
_Publisher = null;
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
index daf46b106..d1a595de0 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Configuration;
using Emby.Dlna.Server;
using Emby.Dlna.Service;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Xml;
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
index 4ed74a684..f07af0464 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
using Emby.Dlna.Service;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Xml;
diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs
index 47e3196e1..13bed6b2f 100644
--- a/Emby.Dlna/PlayTo/Device.cs
+++ b/Emby.Dlna/PlayTo/Device.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Configuration;
using Emby.Dlna.Common;
using Emby.Dlna.Ssdp;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
@@ -108,7 +108,7 @@ namespace Emby.Dlna.PlayTo
public void Start()
{
- _logger.Debug("Dlna Device.Start");
+ _logger.LogDebug("Dlna Device.Start");
_timer = _timerFactory.Create(TimerCallback, null, 1000, Timeout.Infinite);
}
@@ -140,7 +140,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error updating device volume info for {0}", ex, Properties.Name);
+ _logger.LogError(ex, "Error updating device volume info for {DeviceName}", Properties.Name);
}
}
@@ -259,7 +259,7 @@ namespace Emby.Dlna.PlayTo
return false;
}
- _logger.Debug("Setting mute");
+ _logger.LogDebug("Setting mute");
var value = mute ? 1 : 0;
await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value))
@@ -323,7 +323,7 @@ namespace Emby.Dlna.PlayTo
url = url.Replace("&", "&amp;");
- _logger.Debug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header);
+ _logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header);
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
if (command == null)
@@ -507,7 +507,7 @@ namespace Emby.Dlna.PlayTo
if (_disposed)
return;
- //_logger.ErrorException("Error updating device info for {0}", ex, Properties.Name);
+ _logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name);
_connectFailureCount++;
@@ -516,7 +516,7 @@ namespace Emby.Dlna.PlayTo
var action = OnDeviceUnavailable;
if (action != null)
{
- _logger.Debug("Disposing device due to loss of connection");
+ _logger.LogDebug("Disposing device due to loss of connection");
action();
return;
}
@@ -767,7 +767,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Unable to parse xml {0}", ex, trackString);
+ _logger.LogError(ex, "Unable to parse xml {0}", trackString);
return new Tuple<bool, uBaseObject>(true, null);
}
}
@@ -887,7 +887,7 @@ namespace Emby.Dlna.PlayTo
string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
var httpClient = new SsdpHttpClient(_httpClient, _config);
- _logger.Debug("Dlna Device.GetRenderingProtocolAsync");
+ _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync");
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
rendererCommands = TransportCommands.Create(document);
diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs
index 2d0d7c99c..c51f220ef 100644
--- a/Emby.Dlna/PlayTo/PlayToController.cs
+++ b/Emby.Dlna/PlayTo/PlayToController.cs
@@ -7,7 +7,7 @@ using Emby.Dlna.Didl;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.System;
using System;
@@ -156,7 +156,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting progress", ex);
+ _logger.LogError(ex, "Error reporting progress");
}
}
@@ -204,7 +204,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting playback stopped", ex);
+ _logger.LogError(ex, "Error reporting playback stopped");
}
}
@@ -223,7 +223,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting progress", ex);
+ _logger.LogError(ex, "Error reporting progress");
}
}
@@ -247,7 +247,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting progress", ex);
+ _logger.LogError(ex, "Error reporting progress");
}
}
@@ -278,7 +278,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting progress", ex);
+ _logger.LogError(ex, "Error reporting progress");
}
}
@@ -319,7 +319,7 @@ namespace Emby.Dlna.PlayTo
public async Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
{
- _logger.Debug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand);
+ _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand);
var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId);
@@ -351,7 +351,7 @@ namespace Emby.Dlna.PlayTo
}
}
- _logger.Debug("{0} - Playlist created", _session.DeviceName);
+ _logger.LogDebug("{0} - Playlist created", _session.DeviceName);
if (command.PlayCommand == PlayCommand.PlayLast)
{
@@ -532,23 +532,13 @@ namespace Emby.Dlna.PlayTo
return null;
}
- private ILogger GetStreamBuilderLogger()
- {
- if (_config.GetDlnaConfiguration().EnableDebugLog)
- {
- return _logger;
- }
-
- return new NullLogger();
- }
-
private PlaylistItem GetPlaylistItem(BaseItem item, List<MediaSourceInfo> mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
{
if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
{
return new PlaylistItem
{
- StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildVideoItem(new VideoOptions
+ StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions
{
ItemId = item.Id,
MediaSources = mediaSources.ToArray(),
@@ -568,7 +558,7 @@ namespace Emby.Dlna.PlayTo
{
return new PlaylistItem
{
- StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildAudioItem(new AudioOptions
+ StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions
{
ItemId = item.Id,
MediaSources = mediaSources.ToArray(),
@@ -599,7 +589,7 @@ namespace Emby.Dlna.PlayTo
{
Playlist.Clear();
Playlist.AddRange(items);
- _logger.Debug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count);
+ _logger.LogDebug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count);
await SetPlaylistIndex(0).ConfigureAwait(false);
return true;
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index ed3cf311b..47d00aad5 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Session;
using System;
using System.Collections.Generic;
@@ -93,7 +93,7 @@ namespace Emby.Dlna.PlayTo
if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 &&
nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1)
{
- //_logger.Debug("Upnp device {0} does not contain a MediaRenderer device (0).", location);
+ //_logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location);
return;
}
@@ -121,7 +121,7 @@ namespace Emby.Dlna.PlayTo
}
catch (Exception ex)
{
- _logger.ErrorException("Error creating PlayTo device.", ex);
+ _logger.LogError(ex, "Error creating PlayTo device.");
}
finally
{
@@ -155,9 +155,9 @@ namespace Emby.Dlna.PlayTo
private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken)
{
var uri = info.Location;
- _logger.Debug("Attempting to create PlayToController from location {0}", location);
+ _logger.LogDebug("Attempting to create PlayToController from location {0}", location);
- _logger.Debug("Logging session activity from location {0}", location);
+ _logger.LogDebug("Logging session activity from location {0}", location);
string uuid;
if (info.Headers.TryGetValue("USN", out uuid))
{
@@ -237,7 +237,7 @@ namespace Emby.Dlna.PlayTo
SupportsMediaControl = true
});
- _logger.Info("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName);
+ _logger.LogInformation("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName);
}
}
diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs
index 450941489..ae094cc2f 100644
--- a/Emby.Dlna/Service/BaseControlHandler.cs
+++ b/Emby.Dlna/Service/BaseControlHandler.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
using Emby.Dlna.Server;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -20,13 +20,13 @@ namespace Emby.Dlna.Service
private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/";
protected readonly IServerConfigurationManager Config;
- protected readonly ILogger Logger;
+ protected readonly ILogger _logger;
protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
{
Config = config;
- Logger = logger;
+ _logger = logger;
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
}
@@ -52,7 +52,7 @@ namespace Emby.Dlna.Service
}
catch (Exception ex)
{
- Logger.ErrorException("Error processing control request", ex);
+ _logger.LogError(ex, "Error processing control request");
return new ControlErrorHandler().GetResponse(ex);
}
@@ -76,7 +76,7 @@ namespace Emby.Dlna.Service
}
}
- Logger.Debug("Received control request {0}", requestInfo.LocalName);
+ _logger.LogDebug("Received control request {0}", requestInfo.LocalName);
var result = GetResult(requestInfo.LocalName, requestInfo.Headers);
@@ -118,7 +118,7 @@ namespace Emby.Dlna.Service
IsSuccessful = true
};
- //Logger.Debug(xml);
+ //logger.LogDebug(xml);
controlResponse.Headers.Add("EXT", string.Empty);
@@ -244,7 +244,7 @@ namespace Emby.Dlna.Service
var originalHeaders = request.Headers;
var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
- Logger.Debug("Control request. Headers: {0}", headers);
+ _logger.LogDebug("Control request. Headers: {0}", headers);
}
private void LogResponse(ControlResponse response)
@@ -258,7 +258,7 @@ namespace Emby.Dlna.Service
var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray());
//builder.Append(response.Xml);
- Logger.Debug("Control response. Headers: {0}", headers);
+ _logger.LogDebug("Control response. Headers: {0}", headers);
}
}
}
diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs
index bc7f01d97..92b81a7ac 100644
--- a/Emby.Dlna/Service/BaseService.cs
+++ b/Emby.Dlna/Service/BaseService.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Dlna;
using Emby.Dlna.Eventing;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Dlna.Service
{
diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
index a75e065c3..d91f711d2 100644
--- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs
+++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -119,7 +119,7 @@ namespace Emby.Dlna.Ssdp
}
};
- EventHelper.FireEventIfNotNull(DeviceDiscoveredInternal, this, args, _logger);
+ DeviceDiscoveredInternal?.Invoke(this, args);
}
private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
@@ -139,7 +139,7 @@ namespace Emby.Dlna.Ssdp
}
};
- EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger);
+ DeviceLeft?.Invoke(this, args);
}
public void Dispose()
diff --git a/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj b/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj
deleted file mode 100644
index 2c5c92367..000000000
--- a/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj
+++ /dev/null
@@ -1,19 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\ImageMagickSharp\ImageMagickSharp\ImageMagickSharp.csproj" />
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <EmbeddedResource Include="fonts\robotoregular.ttf" />
- </ItemGroup>
-
-</Project>
diff --git a/Emby.Drawing.ImageMagick/ImageHelpers.cs b/Emby.Drawing.ImageMagick/ImageHelpers.cs
deleted file mode 100644
index 866693399..000000000
--- a/Emby.Drawing.ImageMagick/ImageHelpers.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Emby.Drawing.ImageMagick
-{
- internal static class ImageHelpers
- {
- internal static List<string> ProjectPaths(string[] paths, int count)
- {
- if (count <= 0)
- {
- throw new ArgumentOutOfRangeException("count");
- }
- if (paths.Length == 0)
- {
- throw new ArgumentOutOfRangeException("paths");
- }
-
- var list = new List<string>();
-
- AddToList(list, paths, count);
-
- return list.Take(count).ToList();
- }
-
- private static void AddToList(List<string> list, string[] paths, int count)
- {
- while (list.Count < count)
- {
- foreach (var path in paths)
- {
- list.Add(path);
-
- if (list.Count >= count)
- {
- return;
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs
deleted file mode 100644
index 9a313d9d3..000000000
--- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs
+++ /dev/null
@@ -1,354 +0,0 @@
-using System.Threading.Tasks;
-using ImageMagickSharp;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Logging;
-using System;
-using System.IO;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-
-namespace Emby.Drawing.ImageMagick
-{
- public class ImageMagickEncoder : IImageEncoder, IDisposable
- {
- private readonly ILogger _logger;
- private readonly IApplicationPaths _appPaths;
- private readonly Func<IHttpClient> _httpClientFactory;
- private readonly IFileSystem _fileSystem;
- private readonly IEnvironmentInfo _environment;
-
- public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem, IEnvironmentInfo environment)
- {
- _logger = logger;
- _appPaths = appPaths;
- _httpClientFactory = httpClientFactory;
- _fileSystem = fileSystem;
- _environment = environment;
-
- LogVersion();
- }
-
- public string[] SupportedInputFormats
- {
- get
- {
- // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
- return new[]
- {
- "tiff",
- "tif",
- "jpeg",
- "jpg",
- "png",
- "aiff",
- "cr2",
- "crw",
- "dng",
-
- // Remove until supported
- //"nef",
- "orf",
- "pef",
- "arw",
- "webp",
- "gif",
- "bmp",
- "erf",
- "raf",
- "rw2",
- "nrw"
- };
- }
- }
-
- public ImageFormat[] SupportedOutputFormats
- {
- get
- {
- if (_webpAvailable)
- {
- return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
- }
- return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
- }
- }
-
- private void LogVersion()
- {
- _logger.Info("ImageMagick version: " + GetVersion());
- TestWebp();
- Wand.SetMagickThreadCount(1);
- }
-
- public static string GetVersion()
- {
- return Wand.VersionString;
- }
-
- private bool _webpAvailable = true;
- private void TestWebp()
- {
- try
- {
- var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
- _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));
-
- using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
- {
- wand.SaveImage(tmpPath);
- }
- }
- catch
- {
- //_logger.ErrorException("Error loading webp: ", ex);
- _webpAvailable = false;
- }
- }
-
- public ImageSize GetImageSize(string path)
- {
- CheckDisposed();
-
- using (var wand = new MagickWand())
- {
- wand.PingImage(path);
- var img = wand.CurrentImage;
-
- return new ImageSize
- {
- Width = img.Width,
- Height = img.Height
- };
- }
- }
-
- private bool HasTransparency(string path)
- {
- var ext = Path.GetExtension(path);
-
- return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
- }
-
- public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
- {
- // Even if the caller specified 100, don't use it because it takes forever
- quality = Math.Min(quality, 99);
-
- if (string.IsNullOrEmpty(options.BackgroundColor) || !HasTransparency(inputPath))
- {
- using (var originalImage = new MagickWand(inputPath))
- {
- if (options.CropWhiteSpace)
- {
- originalImage.CurrentImage.TrimImage(10);
- }
-
- var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
-
- if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
- {
- // Just spit out the original file if all the options are default
- return inputPath;
- }
-
- var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
-
- var width = Convert.ToInt32(Math.Round(newImageSize.Width));
- var height = Convert.ToInt32(Math.Round(newImageSize.Height));
-
- ScaleImage(originalImage, width, height, options.Blur ?? 0);
-
- if (autoOrient)
- {
- AutoOrientImage(originalImage);
- }
-
- AddForegroundLayer(originalImage, options);
- DrawIndicator(originalImage, width, height, options);
-
- originalImage.CurrentImage.CompressionQuality = quality;
- originalImage.CurrentImage.StripImage();
-
- _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
-
- originalImage.SaveImage(outputPath);
- }
- }
- else
- {
- using (var originalImage = new MagickWand(inputPath))
- {
- var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
-
- var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
-
- var width = Convert.ToInt32(Math.Round(newImageSize.Width));
- var height = Convert.ToInt32(Math.Round(newImageSize.Height));
-
- using (var wand = new MagickWand(width, height, options.BackgroundColor))
- {
- ScaleImage(originalImage, width, height, options.Blur ?? 0);
-
- if (autoOrient)
- {
- AutoOrientImage(originalImage);
- }
-
- wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
-
- AddForegroundLayer(wand, options);
- DrawIndicator(wand, width, height, options);
-
- wand.CurrentImage.CompressionQuality = quality;
- wand.CurrentImage.StripImage();
-
- wand.SaveImage(outputPath);
- }
- }
- }
-
- return outputPath;
- }
-
- private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
- {
- if (string.IsNullOrEmpty(options.ForegroundLayer))
- {
- return;
- }
-
- Double opacity;
- if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
-
- using (var pixel = new PixelWand("#000", opacity))
- using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
- {
- wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
- }
- }
-
- private void AutoOrientImage(MagickWand wand)
- {
- wand.CurrentImage.AutoOrientImage();
- }
-
- public static void RotateImage(MagickWand wand, float angle)
- {
- using (var pixelWand = new PixelWand("none", 1))
- {
- wand.CurrentImage.RotateImage(pixelWand, angle);
- }
- }
-
- private void ScaleImage(MagickWand wand, int width, int height, int blur)
- {
- var useResize = blur > 1;
-
- if (useResize)
- {
- wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur);
- }
- else
- {
- wand.CurrentImage.ScaleImage(width, height);
- }
- }
-
- /// <summary>
- /// Draws the indicator.
- /// </summary>
- /// <param name="wand">The wand.</param>
- /// <param name="imageWidth">Width of the image.</param>
- /// <param name="imageHeight">Height of the image.</param>
- /// <param name="options">The options.</param>
- private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
- {
- if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
- {
- return;
- }
-
- try
- {
- if (options.AddPlayedIndicator)
- {
- var currentImageSize = new ImageSize(imageWidth, imageHeight);
-
- var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
- Task.WaitAll(task);
- }
- else if (options.UnplayedCount.HasValue)
- {
- var currentImageSize = new ImageSize(imageWidth, imageHeight);
-
- new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
- }
-
- if (options.PercentPlayed > 0)
- {
- new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error drawing indicator overlay", ex);
- }
- }
-
- public void CreateImageCollage(ImageCollageOptions options)
- {
- double ratio = options.Width;
- ratio /= options.Height;
-
- if (ratio >= 1.4)
- {
- new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
- }
- else if (ratio >= .9)
- {
- new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
- }
- else
- {
- new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
- }
- }
-
- public string Name
- {
- get { return "ImageMagick"; }
- }
-
- private bool _disposed;
- public void Dispose()
- {
- _disposed = true;
- Wand.CloseEnvironment();
- }
-
- private void CheckDisposed()
- {
- if (_disposed)
- {
- throw new ObjectDisposedException(GetType().Name);
- }
- }
-
- public bool SupportsImageCollageCreation
- {
- get
- {
- return true;
- }
- }
-
- public bool SupportsImageEncoding
- {
- get { return true; }
- }
- }
-}
diff --git a/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs b/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs
deleted file mode 100644
index 90f9d5609..000000000
--- a/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using ImageMagickSharp;
-using System;
-
-namespace Emby.Drawing.ImageMagick
-{
- public class PercentPlayedDrawer
- {
- private const int IndicatorHeight = 8;
-
- public void Process(MagickWand wand, double percent)
- {
- var currentImage = wand.CurrentImage;
- var height = currentImage.Height;
-
- using (var draw = new DrawingWand())
- {
- using (PixelWand pixel = new PixelWand())
- {
- var endX = currentImage.Width - 1;
- var endY = height - 1;
-
- pixel.Color = "black";
- pixel.Opacity = 0.4;
- draw.FillColor = pixel;
- draw.DrawRectangle(0, endY - IndicatorHeight, endX, endY);
-
- double foregroundWidth = endX;
- foregroundWidth *= percent;
- foregroundWidth /= 100;
-
- pixel.Color = "#52B54B";
- pixel.Opacity = 0;
- draw.FillColor = pixel;
- draw.DrawRectangle(0, endY - IndicatorHeight, Convert.ToInt32(Math.Round(foregroundWidth)), endY);
- wand.CurrentImage.DrawImage(draw);
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs b/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs
deleted file mode 100644
index 4dccca0c3..000000000
--- a/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-using ImageMagickSharp;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Drawing;
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Drawing.ImageMagick
-{
- public class PlayedIndicatorDrawer
- {
- private const int FontSize = 52;
- private const int OffsetFromTopRightCorner = 38;
-
- private readonly IApplicationPaths _appPaths;
- private readonly IHttpClient _iHttpClient;
- private readonly IFileSystem _fileSystem;
-
- public PlayedIndicatorDrawer(IApplicationPaths appPaths, IHttpClient iHttpClient, IFileSystem fileSystem)
- {
- _appPaths = appPaths;
- _iHttpClient = iHttpClient;
- _fileSystem = fileSystem;
- }
-
- public async Task DrawPlayedIndicator(MagickWand wand, ImageSize imageSize)
- {
- var x = imageSize.Width - OffsetFromTopRightCorner;
-
- using (var draw = new DrawingWand())
- {
- using (PixelWand pixel = new PixelWand())
- {
- pixel.Color = "#52B54B";
- pixel.Opacity = 0.2;
- draw.FillColor = pixel;
- draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20);
-
- pixel.Opacity = 0;
- pixel.Color = "white";
- draw.FillColor = pixel;
- draw.Font = await DownloadFont("webdings.ttf", "https://github.com/MediaBrowser/Emby.Resources/raw/master/fonts/webdings.ttf", _appPaths, _iHttpClient, _fileSystem).ConfigureAwait(false);
- draw.FontSize = FontSize;
- draw.FontStyle = FontStyleType.NormalStyle;
- draw.TextAlignment = TextAlignType.CenterAlign;
- draw.FontWeight = FontWeightType.RegularStyle;
- draw.TextAntialias = true;
- draw.DrawAnnotation(x + 4, OffsetFromTopRightCorner + 14, "a");
-
- draw.FillColor = pixel;
- wand.CurrentImage.DrawImage(draw);
- }
- }
- }
-
- internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem)
- {
- var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name);
-
- if (fileSystem.FileExists(filePath))
- {
- return filePath;
- }
-
- var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name;
- var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf");
- fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath));
-
- using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath))
- {
- using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read))
- {
- stream.CopyTo(fileStream);
- }
- }
-
- fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath));
-
- try
- {
- fileSystem.CopyFile(tempPath, filePath, false);
- }
- catch (IOException)
- {
-
- }
-
- return tempPath;
- }
-
- internal static async Task<string> DownloadFont(string name, string url, IApplicationPaths paths, IHttpClient httpClient, IFileSystem fileSystem)
- {
- var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name);
-
- if (fileSystem.FileExists(filePath))
- {
- return filePath;
- }
-
- var tempPath = await httpClient.GetTempFile(new HttpRequestOptions
- {
- Url = url,
- Progress = new SimpleProgress<double>()
-
- }).ConfigureAwait(false);
-
- fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath));
-
- try
- {
- fileSystem.CopyFile(tempPath, filePath, false);
- }
- catch (IOException)
- {
-
- }
-
- return tempPath;
- }
- }
-}
diff --git a/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs b/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs
deleted file mode 100644
index 1089607d6..000000000
--- a/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Emby.Drawing.ImageMagick")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Emby.Drawing.ImageMagick")]
-[assembly: AssemblyCopyright("Copyright © 2016")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("6cfee013-6e7c-432b-ac37-cabf0880c69a")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Emby.Drawing.ImageMagick/StripCollageBuilder.cs b/Emby.Drawing.ImageMagick/StripCollageBuilder.cs
deleted file mode 100644
index 26c6c868d..000000000
--- a/Emby.Drawing.ImageMagick/StripCollageBuilder.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-using ImageMagickSharp;
-using MediaBrowser.Common.Configuration;
-using System;
-using System.Collections.Generic;
-
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Drawing.ImageMagick
-{
- public class StripCollageBuilder
- {
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
-
- public StripCollageBuilder(IApplicationPaths appPaths, IFileSystem fileSystem)
- {
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- }
-
- public void BuildPosterCollage(string[] paths, string outputPath, int width, int height)
- {
- using (var wand = BuildPosterCollageWand(paths, width, height))
- {
- wand.SaveImage(outputPath);
- }
- }
-
- public void BuildSquareCollage(string[] paths, string outputPath, int width, int height)
- {
- using (var wand = BuildSquareCollageWand(paths, width, height))
- {
- wand.SaveImage(outputPath);
- }
- }
-
- public void BuildThumbCollage(string[] paths, string outputPath, int width, int height)
- {
- using (var wand = BuildThumbCollageWand(paths, width, height))
- {
- wand.SaveImage(outputPath);
- }
- }
-
- private MagickWand BuildPosterCollageWand(string[] paths, int width, int height)
- {
- var inputPaths = ImageHelpers.ProjectPaths(paths, 3);
- using (var wandImages = new MagickWand(inputPaths.ToArray()))
- {
- var wand = new MagickWand(width, height);
- wand.OpenImage("gradient:#111111-#111111");
- using (var draw = new DrawingWand())
- {
- var iSlice = Convert.ToInt32(width * 0.3);
- int iTrans = Convert.ToInt32(height * .25);
- int iHeight = Convert.ToInt32(height * .65);
- var horizontalImagePadding = Convert.ToInt32(width * 0.0366);
-
- foreach (var element in wandImages.ImageList)
- {
- using (var blackPixelWand = new PixelWand(ColorName.Black))
- {
- int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
- element.Gravity = GravityType.CenterGravity;
- element.BackgroundColor = blackPixelWand;
- element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
- int ix = (int)Math.Abs((iWidth - iSlice) / 2);
- element.CropImage(iSlice, iHeight, ix, 0);
-
- element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
- }
- }
-
- wandImages.SetFirstIterator();
- using (var wandList = wandImages.AppendImages())
- {
- wandList.CurrentImage.TrimImage(1);
- using (var mwr = wandList.CloneMagickWand())
- {
- using (var blackPixelWand = new PixelWand(ColorName.Black))
- {
- using (var greyPixelWand = new PixelWand(ColorName.Grey70))
- {
- mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
- mwr.CurrentImage.FlipImage();
-
- mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
- mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
-
- using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
- {
- mwg.OpenImage("gradient:black-none");
- var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
- mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
-
- wandList.AddImage(mwr);
- int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
- wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .05));
- }
- }
- }
- }
- }
- }
-
- return wand;
- }
- }
-
- private MagickWand BuildThumbCollageWand(string[] paths, int width, int height)
- {
- var inputPaths = ImageHelpers.ProjectPaths(paths, 4);
- using (var wandImages = new MagickWand(inputPaths.ToArray()))
- {
- var wand = new MagickWand(width, height);
- wand.OpenImage("gradient:#111111-#111111");
- using (var draw = new DrawingWand())
- {
- var iSlice = Convert.ToInt32(width * 0.24125);
- int iTrans = Convert.ToInt32(height * .25);
- int iHeight = Convert.ToInt32(height * .70);
- var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
-
- foreach (var element in wandImages.ImageList)
- {
- using (var blackPixelWand = new PixelWand(ColorName.Black))
- {
- int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
- element.Gravity = GravityType.CenterGravity;
- element.BackgroundColor = blackPixelWand;
- element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
- int ix = (int)Math.Abs((iWidth - iSlice) / 2);
- element.CropImage(iSlice, iHeight, ix, 0);
-
- element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
- }
- }
-
- wandImages.SetFirstIterator();
- using (var wandList = wandImages.AppendImages())
- {
- wandList.CurrentImage.TrimImage(1);
- using (var mwr = wandList.CloneMagickWand())
- {
- using (var blackPixelWand = new PixelWand(ColorName.Black))
- {
- using (var greyPixelWand = new PixelWand(ColorName.Grey70))
- {
- mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
- mwr.CurrentImage.FlipImage();
-
- mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
- mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
-
- using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
- {
- mwg.OpenImage("gradient:black-none");
- var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
- mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
-
- wandList.AddImage(mwr);
- int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
- wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .045));
- }
- }
- }
- }
- }
- }
-
- return wand;
- }
- }
-
- private MagickWand BuildSquareCollageWand(string[] paths, int width, int height)
- {
- var inputPaths = ImageHelpers.ProjectPaths(paths, 4);
- var outputWand = new MagickWand(width, height, new PixelWand("none", 1));
- var imageIndex = 0;
- var cellWidth = width/2;
- var cellHeight = height/2;
- for (var x = 0; x < 2; x++)
- {
- for (var y = 0; y < 2; y++)
- {
- using (var temp = new MagickWand(inputPaths[imageIndex]))
- {
- temp.CurrentImage.ScaleImage(cellWidth, cellHeight);
- // draw this image into the strip at the next position
- var xPos = x*cellWidth;
- var yPos = y*cellHeight;
- outputWand.CurrentImage.CompositeImage(temp, CompositeOperator.OverCompositeOp, xPos, yPos);
- }
- imageIndex++;
- }
- }
-
- return outputWand;
- }
- }
-}
diff --git a/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs b/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs
deleted file mode 100644
index ee685c3c5..000000000
--- a/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-using ImageMagickSharp;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Drawing;
-using System.Globalization;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Drawing.ImageMagick
-{
- public class UnplayedCountIndicator
- {
- private const int OffsetFromTopRightCorner = 38;
-
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
-
- public UnplayedCountIndicator(IApplicationPaths appPaths, IFileSystem fileSystem)
- {
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- }
-
- public void DrawUnplayedCountIndicator(MagickWand wand, ImageSize imageSize, int count)
- {
- var x = imageSize.Width - OffsetFromTopRightCorner;
- var text = count.ToString(CultureInfo.InvariantCulture);
-
- using (var draw = new DrawingWand())
- {
- using (PixelWand pixel = new PixelWand())
- {
- pixel.Color = "#52B54B";
- pixel.Opacity = 0.2;
- draw.FillColor = pixel;
- draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20);
-
- pixel.Opacity = 0;
- pixel.Color = "white";
- draw.FillColor = pixel;
- draw.Font = PlayedIndicatorDrawer.ExtractFont("robotoregular.ttf", _appPaths, _fileSystem);
- draw.FontStyle = FontStyleType.NormalStyle;
- draw.TextAlignment = TextAlignType.CenterAlign;
- draw.FontWeight = FontWeightType.RegularStyle;
- draw.TextAntialias = true;
-
- var fontSize = 30;
- var y = OffsetFromTopRightCorner + 11;
-
- if (text.Length == 1)
- {
- x += 1;
- }
- else if (text.Length == 2)
- {
- x += 1;
- }
- else if (text.Length >= 3)
- {
- //x += 1;
- y -= 2;
- fontSize = 24;
- }
-
- draw.FontSize = fontSize;
- draw.DrawAnnotation(x, y, text);
-
- draw.FillColor = pixel;
- wand.CurrentImage.DrawImage(draw);
- }
-
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/DynamicImageHelpers.cs b/Emby.Drawing.Net/DynamicImageHelpers.cs
deleted file mode 100644
index 1910f7840..000000000
--- a/Emby.Drawing.Net/DynamicImageHelpers.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-using System.Collections.Generic;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.Drawing.Imaging;
-using System.IO;
-using MediaBrowser.Common.IO;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Drawing.Net
-{
- public static class DynamicImageHelpers
- {
- public static void CreateThumbCollage(List<string> files,
- IFileSystem fileSystem,
- string file,
- int width,
- int height)
- {
- const int numStrips = 4;
- files = ImageHelpers.ProjectPaths(files, numStrips);
-
- const int rows = 1;
- int cols = numStrips;
-
- int cellWidth = 2 * (width / 3);
- int cellHeight = height;
- var index = 0;
-
- using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
- {
- using (var graphics = Graphics.FromImage(img))
- {
- graphics.CompositingQuality = CompositingQuality.HighQuality;
- graphics.SmoothingMode = SmoothingMode.HighQuality;
- graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
-
- // SourceCopy causes the image to be blank in OSX
- //graphics.CompositingMode = CompositingMode.SourceCopy;
-
- for (var row = 0; row < rows; row++)
- {
- for (var col = 0; col < cols; col++)
- {
- var x = col * (cellWidth / 2);
- var y = row * cellHeight;
-
- if (files.Count > index)
- {
- using (var imgtemp = Image.FromFile(files[index]))
- {
- graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight);
- }
- }
-
- index++;
- }
- }
- img.Save(file);
- }
- }
- }
-
- public static void CreateSquareCollage(List<string> files,
- IFileSystem fileSystem,
- string file,
- int width,
- int height)
- {
- files = ImageHelpers.ProjectPaths(files, 4);
-
- const int rows = 2;
- const int cols = 2;
-
- int singleSize = width / 2;
- var index = 0;
-
- using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
- {
- using (var graphics = Graphics.FromImage(img))
- {
- graphics.CompositingQuality = CompositingQuality.HighQuality;
- graphics.SmoothingMode = SmoothingMode.HighQuality;
- graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
-
- // SourceCopy causes the image to be blank in OSX
- //graphics.CompositingMode = CompositingMode.SourceCopy;
-
- for (var row = 0; row < rows; row++)
- {
- for (var col = 0; col < cols; col++)
- {
- var x = col * singleSize;
- var y = row * singleSize;
-
- using (var imgtemp = Image.FromFile(files[index]))
- {
- graphics.DrawImage(imgtemp, x, y, singleSize, singleSize);
- }
- index++;
- }
- }
- img.Save(file);
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/Emby.Drawing.Net.csproj b/Emby.Drawing.Net/Emby.Drawing.Net.csproj
deleted file mode 100644
index dc9d35dca..000000000
--- a/Emby.Drawing.Net/Emby.Drawing.Net.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <ItemGroup>
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- </ItemGroup>
-
- <PropertyGroup>
- <TargetFramework>netstandard2.0</TargetFramework>
- </PropertyGroup>
-
- <ItemGroup>
- <EmbeddedResource Include="empty.png" />
- </ItemGroup>
-
-</Project>
diff --git a/Emby.Drawing.Net/GDIImageEncoder.cs b/Emby.Drawing.Net/GDIImageEncoder.cs
deleted file mode 100644
index 02e7657dd..000000000
--- a/Emby.Drawing.Net/GDIImageEncoder.cs
+++ /dev/null
@@ -1,282 +0,0 @@
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Logging;
-using System;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.Drawing.Imaging;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Common.IO;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Model.IO;
-using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat;
-using Emby.Drawing;
-
-namespace Emby.Drawing.Net
-{
- public class GDIImageEncoder : IImageEncoder
- {
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
-
- public GDIImageEncoder(IFileSystem fileSystem, ILogger logger)
- {
- _fileSystem = fileSystem;
- _logger = logger;
-
- LogInfo();
- }
-
- private void LogInfo()
- {
- _logger.Info("GDIImageEncoder starting");
- using (var stream = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".empty.png"))
- {
- using (var img = Image.FromStream(stream))
- {
-
- }
- }
- _logger.Info("GDIImageEncoder started");
- }
-
- public string[] SupportedInputFormats
- {
- get
- {
- return new[]
- {
- "png",
- "jpeg",
- "jpg",
- "gif",
- "bmp"
- };
- }
- }
-
- public ImageFormat[] SupportedOutputFormats
- {
- get
- {
- return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
- }
- }
-
- public ImageSize GetImageSize(string path)
- {
- using (var image = Image.FromFile(path))
- {
- return new ImageSize
- {
- Width = image.Width,
- Height = image.Height
- };
- }
- }
-
- private Image GetImage(string path, bool cropWhitespace)
- {
- if (cropWhitespace)
- {
- using (var originalImage = (Bitmap)Image.FromFile(path))
- {
- return originalImage.CropWhitespace();
- }
- }
-
- return Image.FromFile(path);
- }
-
- public void EncodeImage(string inputPath, ImageSize? originalImageSize, string outputPath, bool autoOrient, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
- {
- using (var originalImage = GetImage(inputPath, options.CropWhiteSpace))
- {
- if (options.CropWhiteSpace || !originalImageSize.HasValue)
- {
- originalImageSize = new ImageSize(originalImage.Width, originalImage.Height);
- }
-
- var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
-
- var newWidth = Convert.ToInt32(Math.Round(newImageSize.Width));
- var newHeight = Convert.ToInt32(Math.Round(newImageSize.Height));
-
- // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
- // Also, Webp only supports Format32bppArgb and Format32bppRgb
- var pixelFormat = selectedOutputFormat == ImageFormat.Webp
- ? PixelFormat.Format32bppArgb
- : PixelFormat.Format32bppPArgb;
-
- using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
- {
- // Mono throw an exeception if assign 0 to SetResolution
- if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
- {
- // Preserve the original resolution
- thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
- }
-
- using (var thumbnailGraph = Graphics.FromImage(thumbnail))
- {
- thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
- thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
- thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
- thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
-
- // SourceCopy causes the image to be blank in OSX
- //thumbnailGraph.CompositingMode = !hasPostProcessing ?
- // CompositingMode.SourceCopy :
- // CompositingMode.SourceOver;
-
- SetBackgroundColor(thumbnailGraph, options);
-
- thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
-
- DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
-
- var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat);
-
- // Save to the cache location
- using (var cacheFileStream = _fileSystem.GetFileStream(outputPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, false))
- {
- // Save to the memory stream
- thumbnail.Save(outputFormat, cacheFileStream, quality);
- }
- }
- }
-
- }
- }
-
- /// <summary>
- /// Sets the color of the background.
- /// </summary>
- /// <param name="graphics">The graphics.</param>
- /// <param name="options">The options.</param>
- private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
- {
- var color = options.BackgroundColor;
-
- if (!string.IsNullOrEmpty(color))
- {
- Color drawingColor;
-
- try
- {
- drawingColor = ColorTranslator.FromHtml(color);
- }
- catch
- {
- drawingColor = ColorTranslator.FromHtml("#" + color);
- }
-
- graphics.Clear(drawingColor);
- }
- }
-
- /// <summary>
- /// Draws the indicator.
- /// </summary>
- /// <param name="graphics">The graphics.</param>
- /// <param name="imageWidth">Width of the image.</param>
- /// <param name="imageHeight">Height of the image.</param>
- /// <param name="options">The options.</param>
- private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
- {
- if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
- {
- return;
- }
-
- try
- {
- if (options.AddPlayedIndicator)
- {
- var currentImageSize = new Size(imageWidth, imageHeight);
-
- new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
- }
- else if (options.UnplayedCount.HasValue)
- {
- var currentImageSize = new Size(imageWidth, imageHeight);
-
- new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
- }
-
- if (options.PercentPlayed > 0)
- {
- var currentImageSize = new Size(imageWidth, imageHeight);
-
- new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed);
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error drawing indicator overlay", ex);
- }
- }
-
- /// <summary>
- /// Gets the output format.
- /// </summary>
- /// <param name="image">The image.</param>
- /// <param name="outputFormat">The output format.</param>
- /// <returns>ImageFormat.</returns>
- private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat)
- {
- switch (outputFormat)
- {
- case ImageFormat.Bmp:
- return System.Drawing.Imaging.ImageFormat.Bmp;
- case ImageFormat.Gif:
- return System.Drawing.Imaging.ImageFormat.Gif;
- case ImageFormat.Jpg:
- return System.Drawing.Imaging.ImageFormat.Jpeg;
- case ImageFormat.Png:
- return System.Drawing.Imaging.ImageFormat.Png;
- default:
- return image.RawFormat;
- }
- }
-
- public void CreateImageCollage(ImageCollageOptions options)
- {
- double ratio = options.Width;
- ratio /= options.Height;
-
- if (ratio >= 1.4)
- {
- DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
- }
- else if (ratio >= .9)
- {
- DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
- }
- else
- {
- DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width);
- }
- }
-
- public void Dispose()
- {
- }
-
- public string Name
- {
- get { return "GDI"; }
- }
-
- public bool SupportsImageCollageCreation
- {
- get { return true; }
- }
-
- public bool SupportsImageEncoding
- {
- get { return true; }
- }
- }
-}
diff --git a/Emby.Drawing.Net/ImageExtensions.cs b/Emby.Drawing.Net/ImageExtensions.cs
deleted file mode 100644
index dec2613d0..000000000
--- a/Emby.Drawing.Net/ImageExtensions.cs
+++ /dev/null
@@ -1,217 +0,0 @@
-using System;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.Drawing.Imaging;
-using System.IO;
-
-namespace Emby.Drawing.Net
-{
- public static class ImageExtensions
- {
- /// <summary>
- /// Saves the image.
- /// </summary>
- /// <param name="outputFormat">The output format.</param>
- /// <param name="image">The image.</param>
- /// <param name="toStream">To stream.</param>
- /// <param name="quality">The quality.</param>
- public static void Save(this Image image, ImageFormat outputFormat, Stream toStream, int quality)
- {
- // Use special save methods for jpeg and png that will result in a much higher quality image
- // All other formats use the generic Image.Save
- if (ImageFormat.Jpeg.Equals(outputFormat))
- {
- SaveAsJpeg(image, toStream, quality);
- }
- else if (ImageFormat.Png.Equals(outputFormat))
- {
- image.Save(toStream, ImageFormat.Png);
- }
- else
- {
- image.Save(toStream, outputFormat);
- }
- }
-
- /// <summary>
- /// Saves the JPEG.
- /// </summary>
- /// <param name="image">The image.</param>
- /// <param name="target">The target.</param>
- /// <param name="quality">The quality.</param>
- public static void SaveAsJpeg(this Image image, Stream target, int quality)
- {
- using (var encoderParameters = new EncoderParameters(1))
- {
- encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
- image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters);
- }
- }
-
- private static readonly ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders();
-
- /// <summary>
- /// Gets the image codec info.
- /// </summary>
- /// <param name="mimeType">Type of the MIME.</param>
- /// <returns>ImageCodecInfo.</returns>
- private static ImageCodecInfo GetImageCodecInfo(string mimeType)
- {
- foreach (var encoder in Encoders)
- {
- if (string.Equals(encoder.MimeType, mimeType, StringComparison.OrdinalIgnoreCase))
- {
- return encoder;
- }
- }
-
- return Encoders.Length == 0 ? null : Encoders[0];
- }
-
- /// <summary>
- /// Crops an image by removing whitespace and transparency from the edges
- /// </summary>
- /// <param name="bmp">The BMP.</param>
- /// <returns>Bitmap.</returns>
- /// <exception cref="System.Exception"></exception>
- public static Bitmap CropWhitespace(this Bitmap bmp)
- {
- var width = bmp.Width;
- var height = bmp.Height;
-
- var topmost = 0;
- for (int row = 0; row < height; ++row)
- {
- if (IsAllWhiteRow(bmp, row, width))
- topmost = row;
- else break;
- }
-
- int bottommost = 0;
- for (int row = height - 1; row >= 0; --row)
- {
- if (IsAllWhiteRow(bmp, row, width))
- bottommost = row;
- else break;
- }
-
- int leftmost = 0, rightmost = 0;
- for (int col = 0; col < width; ++col)
- {
- if (IsAllWhiteColumn(bmp, col, height))
- leftmost = col;
- else
- break;
- }
-
- for (int col = width - 1; col >= 0; --col)
- {
- if (IsAllWhiteColumn(bmp, col, height))
- rightmost = col;
- else
- break;
- }
-
- if (rightmost == 0) rightmost = width; // As reached left
- if (bottommost == 0) bottommost = height; // As reached top.
-
- var croppedWidth = rightmost - leftmost;
- var croppedHeight = bottommost - topmost;
-
- if (croppedWidth == 0) // No border on left or right
- {
- leftmost = 0;
- croppedWidth = width;
- }
-
- if (croppedHeight == 0) // No border on top or bottom
- {
- topmost = 0;
- croppedHeight = height;
- }
-
- // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
- var thumbnail = new Bitmap(croppedWidth, croppedHeight, PixelFormat.Format32bppPArgb);
-
- // Preserve the original resolution
- TrySetResolution(thumbnail, bmp.HorizontalResolution, bmp.VerticalResolution);
-
- using (var thumbnailGraph = Graphics.FromImage(thumbnail))
- {
- thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
- thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
- thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
- thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
- thumbnailGraph.CompositingMode = CompositingMode.SourceCopy;
-
- thumbnailGraph.DrawImage(bmp,
- new RectangleF(0, 0, croppedWidth, croppedHeight),
- new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
- GraphicsUnit.Pixel);
- }
- return thumbnail;
- }
-
- /// <summary>
- /// Tries the set resolution.
- /// </summary>
- /// <param name="bmp">The BMP.</param>
- /// <param name="x">The x.</param>
- /// <param name="y">The y.</param>
- private static void TrySetResolution(Bitmap bmp, float x, float y)
- {
- if (x > 0 && y > 0)
- {
- bmp.SetResolution(x, y);
- }
- }
-
- /// <summary>
- /// Determines whether or not a row of pixels is all whitespace
- /// </summary>
- /// <param name="bmp">The BMP.</param>
- /// <param name="row">The row.</param>
- /// <param name="width">The width.</param>
- /// <returns><c>true</c> if [is all white row] [the specified BMP]; otherwise, <c>false</c>.</returns>
- private static bool IsAllWhiteRow(Bitmap bmp, int row, int width)
- {
- for (var i = 0; i < width; ++i)
- {
- if (!IsWhiteSpace(bmp.GetPixel(i, row)))
- {
- return false;
- }
- }
- return true;
- }
-
- /// <summary>
- /// Determines whether or not a column of pixels is all whitespace
- /// </summary>
- /// <param name="bmp">The BMP.</param>
- /// <param name="col">The col.</param>
- /// <param name="height">The height.</param>
- /// <returns><c>true</c> if [is all white column] [the specified BMP]; otherwise, <c>false</c>.</returns>
- private static bool IsAllWhiteColumn(Bitmap bmp, int col, int height)
- {
- for (var i = 0; i < height; ++i)
- {
- if (!IsWhiteSpace(bmp.GetPixel(col, i)))
- {
- return false;
- }
- }
- return true;
- }
-
- /// <summary>
- /// Determines if a color is whitespace
- /// </summary>
- /// <param name="color">The color.</param>
- /// <returns><c>true</c> if [is white space] [the specified color]; otherwise, <c>false</c>.</returns>
- private static bool IsWhiteSpace(Color color)
- {
- return (color.R == 255 && color.G == 255 && color.B == 255) || color.A == 0;
- }
- }
-}
diff --git a/Emby.Drawing.Net/ImageHelpers.cs b/Emby.Drawing.Net/ImageHelpers.cs
deleted file mode 100644
index 1afc47cd0..000000000
--- a/Emby.Drawing.Net/ImageHelpers.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Emby.Drawing.Net
-{
- internal static class ImageHelpers
- {
- internal static List<string> ProjectPaths(List<string> paths, int count)
- {
- if (count <= 0)
- {
- throw new ArgumentOutOfRangeException("count");
- }
- if (paths.Count == 0)
- {
- throw new ArgumentOutOfRangeException("paths");
- }
-
- var list = new List<string>();
-
- AddToList(list, paths, count);
-
- return list.Take(count).ToList();
- }
-
- private static void AddToList(List<string> list, List<string> paths, int count)
- {
- while (list.Count < count)
- {
- foreach (var path in paths)
- {
- list.Add(path);
-
- if (list.Count >= count)
- {
- return;
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/PercentPlayedDrawer.cs b/Emby.Drawing.Net/PercentPlayedDrawer.cs
deleted file mode 100644
index fac15ba47..000000000
--- a/Emby.Drawing.Net/PercentPlayedDrawer.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using System.Drawing;
-
-namespace Emby.Drawing.Net
-{
- public class PercentPlayedDrawer
- {
- private const int IndicatorHeight = 8;
-
- public void Process(Graphics graphics, Size imageSize, double percent)
- {
- var y = imageSize.Height - IndicatorHeight;
-
- using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 0, 0, 0)))
- {
- const int innerX = 0;
- var innerY = y;
- var innerWidth = imageSize.Width;
- var innerHeight = imageSize.Height;
-
- graphics.FillRectangle(backdroundBrush, innerX, innerY, innerWidth, innerHeight);
-
- using (var foregroundBrush = new SolidBrush(Color.FromArgb(82, 181, 75)))
- {
- double foregroundWidth = innerWidth;
- foregroundWidth *= percent;
- foregroundWidth /= 100;
-
- graphics.FillRectangle(foregroundBrush, innerX, innerY, Convert.ToInt32(Math.Round(foregroundWidth)), innerHeight);
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/PlayedIndicatorDrawer.cs b/Emby.Drawing.Net/PlayedIndicatorDrawer.cs
deleted file mode 100644
index 53683e6f4..000000000
--- a/Emby.Drawing.Net/PlayedIndicatorDrawer.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System.Drawing;
-
-namespace Emby.Drawing.Net
-{
- public class PlayedIndicatorDrawer
- {
- private const int IndicatorHeight = 40;
- public const int IndicatorWidth = 40;
- private const int FontSize = 40;
- private const int OffsetFromTopRightCorner = 10;
-
- public void DrawPlayedIndicator(Graphics graphics, Size imageSize)
- {
- var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
-
- using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
- {
- graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
-
- x = imageSize.Width - 45 - OffsetFromTopRightCorner;
-
- using (var font = new Font("Webdings", FontSize, FontStyle.Regular, GraphicsUnit.Pixel))
- {
- using (var fontBrush = new SolidBrush(Color.White))
- {
- graphics.DrawString("a", font, fontBrush, x, OffsetFromTopRightCorner - 2);
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/Properties/AssemblyInfo.cs b/Emby.Drawing.Net/Properties/AssemblyInfo.cs
deleted file mode 100644
index 321c3a297..000000000
--- a/Emby.Drawing.Net/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Emby.Drawing.Net")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Emby.Drawing.Net")]
-[assembly: AssemblyCopyright("Copyright © 2016")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("c97a239e-a96c-4d64-a844-ccf8cc30aecb")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Emby.Drawing.Net/UnplayedCountIndicator.cs b/Emby.Drawing.Net/UnplayedCountIndicator.cs
deleted file mode 100644
index a38abeb32..000000000
--- a/Emby.Drawing.Net/UnplayedCountIndicator.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System.Drawing;
-
-namespace Emby.Drawing.Net
-{
- public class UnplayedCountIndicator
- {
- private const int IndicatorHeight = 41;
- public const int IndicatorWidth = 41;
- private const int OffsetFromTopRightCorner = 10;
-
- public void DrawUnplayedCountIndicator(Graphics graphics, Size imageSize, int count)
- {
- var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
-
- using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
- {
- graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
-
- var text = count.ToString();
-
- x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
- var y = OffsetFromTopRightCorner + 6;
- var fontSize = 24;
-
- if (text.Length == 1)
- {
- x += 10;
- }
- else if (text.Length == 2)
- {
- x += 3;
- }
- else if (text.Length == 3)
- {
- x += 1;
- y += 1;
- fontSize = 20;
- }
-
- using (var font = new Font("Sans-Serif", fontSize, FontStyle.Regular, GraphicsUnit.Pixel))
- {
- using (var fontBrush = new SolidBrush(Color.White))
- {
- graphics.DrawString(text, font, fontBrush, x, y);
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Drawing.Net/empty.png b/Emby.Drawing.Net/empty.png
deleted file mode 100644
index 34b25c436..000000000
--- a/Emby.Drawing.Net/empty.png
+++ /dev/null
Binary files differ
diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs
index 9eb7055b4..0467794dc 100644
--- a/Emby.Drawing.Skia/SkiaEncoder.cs
+++ b/Emby.Drawing.Skia/SkiaEncoder.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using SkiaSharp;
using System;
using System.IO;
@@ -81,7 +81,7 @@ namespace Emby.Drawing.Skia
// test an operation that requires the native library
SKPMColor.PreMultiply(SKColors.Black);
- _logger.Info("SkiaSharp version: " + GetVersion());
+ _logger.LogInformation("SkiaSharp version: " + GetVersion());
}
public static string GetVersion()
@@ -530,7 +530,7 @@ namespace Emby.Drawing.Skia
throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
}
- //_logger.Info("Color type {0}", bitmap.Info.ColorType);
+ //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType);
var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
@@ -548,9 +548,7 @@ namespace Emby.Drawing.Skia
using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
{
// scale image
- var resizeMethod = SKBitmapResizeMethod.Lanczos3;
-
- bitmap.Resize(resizedBitmap, resizeMethod);
+ bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
// If all we're doing is resizing then we can stop now
if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
@@ -558,8 +556,11 @@ namespace Emby.Drawing.Skia
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath))
{
- resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
- return outputPath;
+ using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
+ {
+ pixmap.Encode(outputStream, skiaOutputFormat, quality);
+ return outputPath;
+ }
}
}
@@ -593,8 +594,7 @@ namespace Emby.Drawing.Skia
// If foreground layer present then draw
if (hasForegroundColor)
{
- Double opacity;
- if (!Double.TryParse(options.ForegroundLayer, out opacity))
+ if (!Double.TryParse(options.ForegroundLayer, out double opacity))
{
opacity = .4;
}
@@ -610,7 +610,10 @@ namespace Emby.Drawing.Skia
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath))
{
- saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
+ using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
+ {
+ pixmap.Encode(outputStream, skiaOutputFormat, quality);
+ }
}
}
}
@@ -660,7 +663,7 @@ namespace Emby.Drawing.Skia
}
catch (Exception ex)
{
- _logger.ErrorException("Error drawing indicator overlay", ex);
+ _logger.LogError(ex, "Error drawing indicator overlay");
}
}
diff --git a/Emby.Drawing.Skia/StripCollageBuilder.cs b/Emby.Drawing.Skia/StripCollageBuilder.cs
index 32f0b6585..a98450e08 100644
--- a/Emby.Drawing.Skia/StripCollageBuilder.cs
+++ b/Emby.Drawing.Skia/StripCollageBuilder.cs
@@ -49,7 +49,10 @@ namespace Emby.Drawing.Skia
{
using (var outputStream = new SKFileWStream(outputPath))
{
- bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
+ using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
+ {
+ pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
+ }
}
}
}
@@ -60,7 +63,10 @@ namespace Emby.Drawing.Skia
{
using (var outputStream = new SKFileWStream(outputPath))
{
- bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
+ using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
+ {
+ pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
+ }
}
}
}
@@ -83,9 +89,8 @@ namespace Emby.Drawing.Skia
for (int i = 0; i < 4; i++)
{
- int newIndex;
- using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex))
+ using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
{
imageIndex = newIndex;
@@ -98,7 +103,7 @@ namespace Emby.Drawing.Skia
int iWidth = (int)Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height);
using (var resizeBitmap = new SKBitmap(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
{
- currentBitmap.Resize(resizeBitmap, SKBitmapResizeMethod.Lanczos3);
+ currentBitmap.ScalePixels(resizeBitmap, SKFilterQuality.High);
// crop image
int ix = (int)Math.Abs((iWidth - iSlice) / 2);
using (var image = SKImage.FromBitmap(resizeBitmap))
@@ -116,7 +121,7 @@ namespace Emby.Drawing.Skia
using (var reflectionBitmap = new SKBitmap(croppedBitmap.Width, croppedBitmap.Height / 2, croppedBitmap.ColorType, croppedBitmap.AlphaType))
{
// resize to half height
- croppedBitmap.Resize(reflectionBitmap, SKBitmapResizeMethod.Lanczos3);
+ currentBitmap.ScalePixels(reflectionBitmap, SKFilterQuality.High);
using (var flippedBitmap = new SKBitmap(reflectionBitmap.Width, reflectionBitmap.Height, reflectionBitmap.ColorType, reflectionBitmap.AlphaType))
using (var flippedCanvas = new SKCanvas(flippedBitmap))
@@ -164,8 +169,7 @@ namespace Emby.Drawing.Skia
currentIndex = 0;
}
- SKEncodedOrigin origin;
- bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out origin);
+ bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out SKEncodedOrigin origin);
imagesTested[currentIndex] = 0;
@@ -194,9 +198,8 @@ namespace Emby.Drawing.Skia
{
for (var y = 0; y < 2; y++)
{
- int newIndex;
- using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex))
+ using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
{
imageIndex = newIndex;
@@ -208,7 +211,7 @@ namespace Emby.Drawing.Skia
using (var resizedBitmap = new SKBitmap(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
{
// scale image
- currentBitmap.Resize(resizedBitmap, SKBitmapResizeMethod.Lanczos3);
+ currentBitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
// draw this image into the strip at the next position
var xPos = x * cellWidth;
diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs
index 121e20deb..7b819c2fd 100644
--- a/Emby.Drawing/Common/ImageHeader.cs
+++ b/Emby.Drawing/Common/ImageHeader.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -235,4 +235,4 @@ namespace Emby.Drawing.Common
throw new ArgumentException(ErrorMessage);
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj
index 3fa60fad1..5ffaaed27 100644
--- a/Emby.Drawing/Emby.Drawing.csproj
+++ b/Emby.Drawing/Emby.Drawing.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs
index 495ba99a6..6a67be56d 100644
--- a/Emby.Drawing/ImageProcessor.cs
+++ b/Emby.Drawing/ImageProcessor.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Concurrent;
@@ -261,7 +261,7 @@ namespace Emby.Drawing
//if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient)
//{
// // Just spit out the original file if all the options are default
- // _logger.Info("Returning original image {0}", originalImagePath);
+ // _logger.LogInformation("Returning original image {0}", originalImagePath);
// return new ValueTuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
//}
@@ -302,7 +302,7 @@ namespace Emby.Drawing
{
// Decoder failed to decode it
#if DEBUG
- _logger.ErrorException("Error encoding image", ex);
+ _logger.LogError(ex, "Error encoding image");
#endif
// Just spit out the original file if all the options are default
return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
@@ -310,7 +310,7 @@ namespace Emby.Drawing
catch (Exception ex)
{
// If it fails for whatever reason, return the original image
- _logger.ErrorException("Error encoding image", ex);
+ _logger.LogError(ex, "Error encoding image");
// Just spit out the original file if all the options are default
return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
@@ -464,7 +464,7 @@ namespace Emby.Drawing
}
var path = info.Path;
- _logger.Info("Getting image size for item {0} {1}", item.GetType().Name, path);
+ _logger.LogInformation("Getting image size for item {0} {1}", item.GetType().Name, path);
var size = GetImageSize(path, allowSlowMethods);
@@ -603,7 +603,7 @@ namespace Emby.Drawing
}
catch (Exception ex)
{
- _logger.ErrorException("Image conversion failed for {0}", ex, originalImagePath);
+ _logger.LogError(ex, "Image conversion failed for {originalImagePath}", originalImagePath);
}
}
@@ -646,21 +646,21 @@ namespace Emby.Drawing
var cacheGuid = GetImageCacheTag(item, image, enhancers);
// Enhance if we have enhancers
- var ehnancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
+ var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
- var ehnancedImagePath = ehnancedImageInfo.Item1;
+ var enhancedImagePath = enhancedImageInfo.Item1;
// If the path changed update dateModified
- if (!string.Equals(ehnancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
{
- var treatmentRequiresTransparency = ehnancedImageInfo.Item2;
+ var treatmentRequiresTransparency = enhancedImageInfo.Item2;
- return new ValueTuple<string, DateTime, bool>(ehnancedImagePath, _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath), treatmentRequiresTransparency);
+ return new ValueTuple<string, DateTime, bool>(enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency);
}
}
catch (Exception ex)
{
- _logger.ErrorException("Error enhancing image", ex);
+ _logger.LogError(ex, "Error enhancing image");
}
return new ValueTuple<string, DateTime, bool>(originalImagePath, dateModified, inputImageSupportsTransparency);
@@ -827,11 +827,11 @@ namespace Emby.Drawing
public void CreateImageCollage(ImageCollageOptions options)
{
- _logger.Info("Creating image collage and saving to {0}", options.OutputPath);
+ _logger.LogInformation("Creating image collage and saving to {0}", options.OutputPath);
_imageEncoder.CreateImageCollage(options);
- _logger.Info("Completed creation of image collage and saved to {0}", options.OutputPath);
+ _logger.LogInformation("Completed creation of image collage and saved to {0}", options.OutputPath);
}
public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType)
@@ -853,7 +853,7 @@ namespace Emby.Drawing
}
catch (Exception ex)
{
- _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
+ _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name);
}
}
diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
index 620d3bae9..faaed482a 100644
--- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
+++ b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
@@ -4,7 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
using System.Runtime.InteropServices;
@@ -20,7 +20,7 @@ namespace IsoMounter
private readonly IEnvironmentInfo EnvironmentInfo;
private readonly bool ExecutablesAvailable;
private readonly IFileSystem FileSystem;
- private readonly ILogger Logger;
+ private readonly ILogger _logger;
private readonly string MountCommand;
private readonly string MountPointRoot;
private readonly IProcessFactory ProcessFactory;
@@ -36,24 +36,24 @@ namespace IsoMounter
EnvironmentInfo = environment;
FileSystem = fileSystem;
- Logger = logger;
+ _logger = logger;
ProcessFactory = processFactory;
MountPointRoot = FileSystem.DirectorySeparatorChar + "tmp" + FileSystem.DirectorySeparatorChar + "Emby";
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] System PATH is currently set to [{1}].",
Name,
EnvironmentInfo.GetEnvironmentVariable("PATH") ?? ""
);
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] System path separator is [{1}].",
Name,
EnvironmentInfo.PathSeparator
);
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] Mount point root is [{1}].",
Name,
MountPointRoot
@@ -65,7 +65,7 @@ namespace IsoMounter
SudoCommand = GetFullPathForExecutable("sudo");
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Using version of [sudo] located at [{1}].",
Name,
SudoCommand
@@ -73,7 +73,7 @@ namespace IsoMounter
MountCommand = GetFullPathForExecutable("mount");
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Using version of [mount] located at [{1}].",
Name,
MountCommand
@@ -81,7 +81,7 @@ namespace IsoMounter
UmountCommand = GetFullPathForExecutable("umount");
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Using version of [umount] located at [{1}].",
Name,
UmountCommand
@@ -119,7 +119,7 @@ namespace IsoMounter
{
if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux) {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].",
Name,
path,
@@ -182,7 +182,7 @@ namespace IsoMounter
return;
}
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Disposing [{1}].",
Name,
disposing.ToString()
@@ -230,7 +230,7 @@ namespace IsoMounter
var uid = getuid();
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] Our current UID is [{1}], GetUserId() returned [{2}].",
Name,
uid.ToString(),
@@ -260,35 +260,29 @@ namespace IsoMounter
}
);
- try {
-
+ try
+ {
process.Start();
//StreamReader outputReader = process.StandardOutput.;
//StreamReader errorReader = process.StandardError;
- Logger.Debug(
- "[{0}] Standard output from process is [{1}].",
+ _logger.LogDebug(
+ "[{Name}] Standard output from process is [{Error}].",
Name,
process.StandardOutput.ReadToEnd()
);
- Logger.Debug(
- "[{0}] Standard error from process is [{1}].",
+ _logger.LogDebug(
+ "[{Name}] Standard error from process is [{Error}].",
Name,
process.StandardError.ReadToEnd()
);
-
- } catch (Exception ex) {
-
+ }
+ catch (Exception ex)
+ {
processFailed = true;
-
- Logger.Debug(
- "[{0}] Unhandled exception executing command, exception is [{1}].",
- Name,
- ex.Message
- );
-
+ _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
}
if (!processFailed && process.ExitCode == 0) {
@@ -308,14 +302,14 @@ namespace IsoMounter
if (!string.IsNullOrEmpty(isoPath)) {
- Logger.Info(
- "[{0}] Attempting to mount [{1}].",
+ _logger.LogInformation(
+ "[{Name}] Attempting to mount [{Path}].",
Name,
isoPath
);
- Logger.Debug(
- "[{0}] ISO will be mounted at [{1}].",
+ _logger.LogDebug(
+ "[{Name}] ISO will be mounted at [{Path}].",
Name,
mountPoint
);
@@ -326,11 +320,16 @@ namespace IsoMounter
}
- try {
+ try
+ {
FileSystem.CreateDirectory(mountPoint);
- } catch (UnauthorizedAccessException) {
+ }
+ catch (UnauthorizedAccessException)
+ {
throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
- } catch (Exception) {
+ }
+ catch (Exception)
+ {
throw new IOException("Unable to create mount point for " + isoPath);
}
@@ -342,7 +341,7 @@ namespace IsoMounter
cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
}
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] Mount command [{1}], mount arguments [{2}].",
Name,
cmdFilename,
@@ -351,7 +350,7 @@ namespace IsoMounter
if (ExecuteCommand(cmdFilename, cmdArguments)) {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] ISO mount completed successfully.",
Name
);
@@ -360,23 +359,18 @@ namespace IsoMounter
} else {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] ISO mount completed with errors.",
Name
);
- try {
-
+ try
+ {
FileSystem.DeleteDirectory(mountPoint, false);
-
- } catch (Exception ex) {
-
- Logger.Info(
- "[{0}] Unhandled exception removing mount point, exception is [{1}].",
- Name,
- ex.Message
- );
-
+ }
+ catch (Exception ex)
+ {
+ _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
}
mountedISO = null;
@@ -395,7 +389,7 @@ namespace IsoMounter
if (mount != null) {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
Name,
mount.IsoPath,
@@ -416,7 +410,7 @@ namespace IsoMounter
cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
}
- Logger.Debug(
+ _logger.LogDebug(
"[{0}] Umount command [{1}], umount arguments [{2}].",
Name,
cmdFilename,
@@ -425,34 +419,28 @@ namespace IsoMounter
if (ExecuteCommand(cmdFilename, cmdArguments)) {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] ISO unmount completed successfully.",
Name
);
} else {
- Logger.Info(
+ _logger.LogInformation(
"[{0}] ISO unmount completed with errors.",
Name
);
}
- try {
-
+ try
+ {
FileSystem.DeleteDirectory(mount.MountedPath, false);
-
- } catch (Exception ex) {
-
- Logger.Info(
- "[{0}] Unhandled exception removing mount point, exception is [{1}].",
- Name,
- ex.Message
- );
-
}
-
+ catch (Exception ex)
+ {
+ _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
+ }
}
#endregion
diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs
index 9c60f9d0a..edd26f08d 100644
--- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs
+++ b/Emby.IsoMounting/IsoMounter/LinuxMount.cs
@@ -79,4 +79,3 @@ namespace IsoMounter
}
}
-
diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs
index bb348d267..fa8fdd9c1 100644
--- a/Emby.Notifications/NotificationManager.cs
+++ b/Emby.Notifications/NotificationManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Notifications;
using System;
using System.Collections.Generic;
@@ -25,11 +25,11 @@ namespace Emby.Notifications
private INotificationService[] _services;
private INotificationTypeFactory[] _typeFactories;
- public NotificationManager(ILogManager logManager, IUserManager userManager, IServerConfigurationManager config)
+ public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config)
{
_userManager = userManager;
_config = config;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
}
private NotificationOptions GetConfiguration()
@@ -126,7 +126,7 @@ namespace Emby.Notifications
User = user
};
- _logger.Debug("Sending notification via {0} to user {1}", service.Name, user.Name);
+ _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Name);
try
{
@@ -134,7 +134,7 @@ namespace Emby.Notifications
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending notification to {0}", ex, service.Name);
+ _logger.LogError(ex, "Error sending notification to {0}", service.Name);
}
}
@@ -146,7 +146,7 @@ namespace Emby.Notifications
}
catch (Exception ex)
{
- _logger.ErrorException("Error in IsEnabledForUser", ex);
+ _logger.LogError(ex, "Error in IsEnabledForUser");
return false;
}
}
@@ -177,7 +177,7 @@ namespace Emby.Notifications
}
catch (Exception ex)
{
- _logger.ErrorException("Error in GetNotificationTypes", ex);
+ _logger.LogError(ex, "Error in GetNotificationTypes");
return new List<NotificationTypeInfo>();
}
diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs
index 3cadad6c8..101f9706c 100644
--- a/Emby.Notifications/Notifications.cs
+++ b/Emby.Notifications/Notifications.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Notifications;
using MediaBrowser.Model.Tasks;
using System;
@@ -137,7 +137,7 @@ namespace Emby.Notifications
var notification = new NotificationRequest
{
- Description = "Please see emby.media for details.",
+ Description = "Please see jellyfin.media for details.",
NotificationType = type,
Name = _localization.GetLocalizedString("NewVersionIsAvailable")
};
@@ -273,7 +273,7 @@ namespace Emby.Notifications
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending notification", ex);
+ _logger.LogError(ex, "Error sending notification");
}
}
diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj
index e945ff444..3ecab9176 100644
--- a/Emby.Photos/Emby.Photos.csproj
+++ b/Emby.Photos/Emby.Photos.csproj
@@ -7,7 +7,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs
index 3e998997a..726fd1d79 100644
--- a/Emby.Photos/PhotoProvider.cs
+++ b/Emby.Photos/PhotoProvider.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using TagLib;
using TagLib.IFD;
using TagLib.IFD.Entries;
@@ -170,9 +170,9 @@ namespace Emby.Photos
}
}
}
- catch (Exception e)
+ catch (Exception ex)
{
- _logger.ErrorException("Image Provider - Error reading image tag for {0}", e, item.Path);
+ _logger.LogError(ex, "Image Provider - Error reading image tag for {0}", item.Path);
}
}
diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
index e4b65b58d..3f7b907a9 100644
--- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
+++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
@@ -10,7 +10,7 @@ using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Updates;
using System;
@@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.Activity
if (item == null)
{
- //_logger.Warn("PlaybackStopped reported with null media info.");
+ //_logger.LogWarning("PlaybackStopped reported with null media info.");
return;
}
@@ -160,7 +160,7 @@ namespace Emby.Server.Implementations.Activity
if (item == null)
{
- //_logger.Warn("PlaybackStart reported with null media info.");
+ //_logger.LogWarning("PlaybackStart reported with null media info.");
return;
}
@@ -284,7 +284,7 @@ namespace Emby.Server.Implementations.Activity
Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
Type = "AuthenticationFailed",
ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
- Severity = LogSeverity.Error
+ Severity = LogLevel.Error
});
}
@@ -468,7 +468,7 @@ namespace Emby.Server.Implementations.Activity
Type = NotificationType.TaskFailed.ToString(),
Overview = string.Join(Environment.NewLine, vals.ToArray()),
ShortOverview = runningTime,
- Severity = LogSeverity.Error
+ Severity = LogLevel.Error
});
}
}
diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs
index 047bebf23..0bb44a9d5 100644
--- a/Emby.Server.Implementations/Activity/ActivityManager.cs
+++ b/Emby.Server.Implementations/Activity/ActivityManager.cs
@@ -1,8 +1,7 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using System;
using System.Linq;
@@ -30,7 +29,7 @@ namespace Emby.Server.Implementations.Activity
_repo.Create(entry);
- EventHelper.FireEventIfNotNull(EntryCreated, this, new GenericEventArgs<ActivityLogEntry>(entry), _logger);
+ EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(entry));
}
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs
index 7f76d724b..91a4a5fd4 100644
--- a/Emby.Server.Implementations/Activity/ActivityRepository.cs
+++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs
@@ -6,7 +6,7 @@ using System.Linq;
using Emby.Server.Implementations.Data;
using MediaBrowser.Controller;
using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using SQLitePCL.pretty;
using MediaBrowser.Model.Extensions;
@@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Activity
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading database file. Will reset and retry.", ex);
+ Logger.LogError(ex, "Error loading database file. Will reset and retry.");
FileSystem.DeleteFile(DbFilePath);
@@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.Activity
}
catch (Exception ex)
{
- Logger.ErrorException("Error migrating activity log database", ex);
+ Logger.LogError(ex, "Error migrating activity log database");
}
}
@@ -87,36 +87,34 @@ namespace Emby.Server.Implementations.Activity
}
using (WriteLock.Write())
+ using (var connection = CreateConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(db =>
{
- connection.RunInTransaction(db =>
+ using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"))
{
- using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)"))
+ statement.TryBind("@Name", entry.Name);
+
+ statement.TryBind("@Overview", entry.Overview);
+ statement.TryBind("@ShortOverview", entry.ShortOverview);
+ statement.TryBind("@Type", entry.Type);
+ statement.TryBind("@ItemId", entry.ItemId);
+
+ if (entry.UserId.Equals(Guid.Empty))
{
- statement.TryBind("@Name", entry.Name);
-
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
+ statement.TryBindNull("@UserId");
}
- }, TransactionMode);
- }
+ else
+ {
+ statement.TryBind("@UserId", entry.UserId.ToString("N"));
+ }
+
+ statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
+ statement.TryBind("@LogSeverity", entry.Severity.ToString());
+
+ statement.MoveNext();
+ }
+ }, TransactionMode);
}
}
@@ -128,132 +126,128 @@ namespace Emby.Server.Implementations.Activity
}
using (WriteLock.Write())
+ using (var connection = CreateConnection())
{
- using (var connection = CreateConnection())
+ connection.RunInTransaction(db =>
{
- connection.RunInTransaction(db =>
+ using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id"))
{
- using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id"))
+ statement.TryBind("@Id", entry.Id);
+
+ statement.TryBind("@Name", entry.Name);
+ statement.TryBind("@Overview", entry.Overview);
+ statement.TryBind("@ShortOverview", entry.ShortOverview);
+ statement.TryBind("@Type", entry.Type);
+ statement.TryBind("@ItemId", entry.ItemId);
+
+ if (entry.UserId.Equals(Guid.Empty))
{
- statement.TryBind("@Id", entry.Id);
-
- statement.TryBind("@Name", entry.Name);
- statement.TryBind("@Overview", entry.Overview);
- statement.TryBind("@ShortOverview", entry.ShortOverview);
- statement.TryBind("@Type", entry.Type);
- statement.TryBind("@ItemId", entry.ItemId);
-
- if (entry.UserId.Equals(Guid.Empty))
- {
- statement.TryBindNull("@UserId");
- }
- else
- {
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
- }
-
- statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
- statement.TryBind("@LogSeverity", entry.Severity.ToString());
-
- statement.MoveNext();
+ statement.TryBindNull("@UserId");
}
- }, TransactionMode);
- }
+ else
+ {
+ statement.TryBind("@UserId", entry.UserId.ToString("N"));
+ }
+
+ statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
+ statement.TryBind("@LogSeverity", entry.Severity.ToString());
+
+ statement.MoveNext();
+ }
+ }, TransactionMode);
}
}
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
{
using (WriteLock.Read())
+ using (var connection = CreateConnection(true))
{
- using (var connection = CreateConnection(true))
- {
- var commandText = BaseActivitySelectText;
- var whereClauses = new List<string>();
+ var commandText = BaseActivitySelectText;
+ var whereClauses = new List<string>();
- if (minDate.HasValue)
+ if (minDate.HasValue)
+ {
+ whereClauses.Add("DateCreated>=@DateCreated");
+ }
+ if (hasUserId.HasValue)
+ {
+ if (hasUserId.Value)
{
- whereClauses.Add("DateCreated>=@DateCreated");
+ whereClauses.Add("UserId not null");
}
- if (hasUserId.HasValue)
+ else
{
- if (hasUserId.Value)
- {
- whereClauses.Add("UserId not null");
- }
- else
- {
- whereClauses.Add("UserId is null");
- }
+ whereClauses.Add("UserId is null");
}
+ }
- var whereTextWithoutPaging = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- if (startIndex.HasValue && startIndex.Value > 0)
- {
- var pagingWhereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
+ var whereTextWithoutPaging = whereClauses.Count == 0 ?
+ string.Empty :
+ " where " + string.Join(" AND ", whereClauses.ToArray());
- whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
- pagingWhereText,
- startIndex.Value.ToString(_usCulture)));
- }
-
- var whereText = whereClauses.Count == 0 ?
+ if (startIndex.HasValue && startIndex.Value > 0)
+ {
+ var pagingWhereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
- commandText += whereText;
+ whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
+ pagingWhereText,
+ startIndex.Value.ToString(_usCulture)));
+ }
- commandText += " ORDER BY DateCreated DESC";
+ var whereText = whereClauses.Count == 0 ?
+ string.Empty :
+ " where " + string.Join(" AND ", whereClauses.ToArray());
- if (limit.HasValue)
- {
- commandText += " LIMIT " + limit.Value.ToString(_usCulture);
- }
+ commandText += whereText;
- var statementTexts = new List<string>();
- statementTexts.Add(commandText);
- statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
+ commandText += " ORDER BY DateCreated DESC";
- return connection.RunInTransaction(db =>
- {
- var list = new List<ActivityLogEntry>();
- var result = new QueryResult<ActivityLogEntry>();
+ if (limit.HasValue)
+ {
+ commandText += " LIMIT " + limit.Value.ToString(_usCulture);
+ }
- var statements = PrepareAllSafe(db, statementTexts).ToList();
+ var statementTexts = new List<string>();
+ statementTexts.Add(commandText);
+ statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
+
+ return connection.RunInTransaction(db =>
+ {
+ var list = new List<ActivityLogEntry>();
+ var result = new QueryResult<ActivityLogEntry>();
- using (var statement = statements[0])
+ var statements = PrepareAllSafe(db, statementTexts).ToList();
+
+ using (var statement = statements[0])
+ {
+ if (minDate.HasValue)
{
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
-
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(GetEntry(row));
- }
+ statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
}
- using (var statement = statements[1])
+ foreach (var row in statement.ExecuteQuery())
{
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
+ list.Add(GetEntry(row));
+ }
+ }
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ using (var statement = statements[1])
+ {
+ if (minDate.HasValue)
+ {
+ statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
}
- result.Items = list.ToArray();
- return result;
+ result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ }
- }, ReadTransactionMode);
- }
+ result.Items = list.ToArray();
+ return result;
+
+ }, ReadTransactionMode);
}
}
@@ -308,7 +302,7 @@ namespace Emby.Server.Implementations.Activity
index++;
if (reader[index].SQLiteType != SQLiteType.Null)
{
- info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader[index].ToString(), true);
+ info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true);
}
return info;
diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
index 52e421374..3e12bc0b6 100644
--- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
+++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
@@ -1,5 +1,4 @@
-using System;
-using System.IO;
+using System.IO;
using MediaBrowser.Common.Configuration;
namespace Emby.Server.Implementations.AppBase
@@ -13,10 +12,16 @@ namespace Emby.Server.Implementations.AppBase
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationPaths"/> class.
/// </summary>
- protected BaseApplicationPaths(string programDataPath, string appFolderPath)
+ protected BaseApplicationPaths(
+ string programDataPath,
+ string appFolderPath,
+ string logDirectoryPath = null,
+ string configurationDirectoryPath = null)
{
ProgramDataPath = programDataPath;
ProgramSystemPath = appFolderPath;
+ LogDirectoryPath = logDirectoryPath;
+ ConfigurationDirectoryPath = configurationDirectoryPath;
}
public string ProgramDataPath { get; private set; }
@@ -107,6 +112,11 @@ namespace Emby.Server.Implementations.AppBase
}
/// <summary>
+ /// The _log directory
+ /// </summary>
+ private string _logDirectoryPath;
+
+ /// <summary>
/// Gets the path to the log directory
/// </summary>
/// <value>The log directory path.</value>
@@ -114,11 +124,27 @@ namespace Emby.Server.Implementations.AppBase
{
get
{
- return Path.Combine(ProgramDataPath, "logs");
+ if (string.IsNullOrEmpty(_logDirectoryPath))
+ {
+ _logDirectoryPath = Path.Combine(ProgramDataPath, "logs");
+
+ Directory.CreateDirectory(_logDirectoryPath);
+ }
+
+ return _logDirectoryPath;
+ }
+ set
+ {
+ _logDirectoryPath = value;
}
}
/// <summary>
+ /// The _config directory
+ /// </summary>
+ private string _configurationDirectoryPath;
+
+ /// <summary>
/// Gets the path to the application configuration root directory
/// </summary>
/// <value>The configuration directory path.</value>
@@ -126,7 +152,18 @@ namespace Emby.Server.Implementations.AppBase
{
get
{
- return Path.Combine(ProgramDataPath, "config");
+ if (string.IsNullOrEmpty(_configurationDirectoryPath))
+ {
+ _configurationDirectoryPath = Path.Combine(ProgramDataPath, "config");
+
+ Directory.CreateDirectory(_configurationDirectoryPath);
+ }
+
+ return _configurationDirectoryPath;
+ }
+ set
+ {
+ _configurationDirectoryPath = value;
}
}
diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
index 385b4bd51..bc5168fe8 100644
--- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
+++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
namespace Emby.Server.Implementations.AppBase
@@ -97,14 +97,14 @@ namespace Emby.Server.Implementations.AppBase
/// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
/// </summary>
/// <param name="applicationPaths">The application paths.</param>
- /// <param name="logManager">The log manager.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
/// <param name="xmlSerializer">The XML serializer.</param>
- protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
+ protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
{
CommonApplicationPaths = applicationPaths;
XmlSerializer = xmlSerializer;
FileSystem = fileSystem;
- Logger = logManager.GetLogger(GetType().Name);
+ Logger = loggerFactory.CreateLogger(GetType().Name);
UpdateCachePath();
}
@@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.AppBase
/// </summary>
public void SaveConfiguration()
{
- Logger.Info("Saving system configuration");
+ Logger.LogInformation("Saving system configuration");
var path = CommonApplicationPaths.SystemConfigurationFilePath;
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path));
@@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.AppBase
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading configuration file: {0}", ex, path);
+ Logger.LogError(ex, "Error loading configuration file: {path}", path);
return Activator.CreateInstance(configurationType);
}
@@ -283,12 +283,11 @@ namespace Emby.Server.Implementations.AppBase
validatingStore.Validate(currentConfiguration, configuration);
}
- EventHelper.FireEventIfNotNull(NamedConfigurationUpdating, this, new ConfigurationUpdateEventArgs
+ NamedConfigurationUpdating?.Invoke( this, new ConfigurationUpdateEventArgs
{
Key = key,
NewConfiguration = configuration
-
- }, Logger);
+ });
_configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
@@ -305,12 +304,11 @@ namespace Emby.Server.Implementations.AppBase
protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
{
- EventHelper.FireEventIfNotNull(NamedConfigurationUpdated, this, new ConfigurationUpdateEventArgs
+ NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
{
Key = key,
NewConfiguration = configuration
-
- }, Logger);
+ });
}
public Type GetConfigurationType(string key)
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index ad15b015d..fb053f0e4 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -48,13 +48,11 @@ using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Connect;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
@@ -80,10 +78,8 @@ using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.News;
using MediaBrowser.Model.Reflection;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
@@ -117,6 +113,7 @@ using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certif
using MediaBrowser.Controller.Authentication;
using System.Diagnostics;
using ServiceStack.Text.Jsv;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations
{
@@ -202,10 +199,10 @@ namespace Emby.Server.Implementations
public IPlugin[] Plugins { get; protected set; }
/// <summary>
- /// Gets or sets the log manager.
+ /// Gets or sets the logger factory.
/// </summary>
- /// <value>The log manager.</value>
- public ILogManager LogManager { get; protected set; }
+ /// <value>The logger factory.</value>
+ public ILoggerFactory LoggerFactory { get; protected set; }
/// <summary>
/// Gets the application paths.
@@ -275,12 +272,12 @@ namespace Emby.Server.Implementations
/// <returns>IConfigurationManager.</returns>
protected IConfigurationManager GetConfigurationManager()
{
- return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer, FileSystemManager);
+ return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
}
protected virtual IResourceFileManager CreateResourceFileManager()
{
- return new ResourceFileManager(HttpResultFactory, LogManager.GetLogger("ResourceManager"), FileSystemManager);
+ return new ResourceFileManager(HttpResultFactory, LoggerFactory.CreateLogger("ResourceManager"), FileSystemManager);
}
/// <summary>
@@ -370,9 +367,7 @@ namespace Emby.Server.Implementations
protected IAuthService AuthService { get; private set; }
public StartupOptions StartupOptions { get; private set; }
- protected readonly string ReleaseAssetFilename;
- internal IPowerManagement PowerManagement { get; private set; }
internal IImageEncoder ImageEncoder { get; private set; }
protected IProcessFactory ProcessFactory { get; private set; }
@@ -391,11 +386,9 @@ namespace Emby.Server.Implementations
/// Initializes a new instance of the <see cref="ApplicationHost" /> class.
/// </summary>
public ApplicationHost(ServerApplicationPaths applicationPaths,
- ILogManager logManager,
+ ILoggerFactory loggerFactory,
StartupOptions options,
IFileSystem fileSystem,
- IPowerManagement powerManagement,
- string releaseAssetFilename,
IEnvironmentInfo environmentInfo,
IImageEncoder imageEncoder,
ISystemEvents systemEvents,
@@ -405,7 +398,7 @@ namespace Emby.Server.Implementations
// hack alert, until common can target .net core
BaseExtensions.CryptographyProvider = CryptographyProvider;
- XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
+ XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory.CreateLogger("XmlSerializer"));
NetworkManager = networkManager;
networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
@@ -413,22 +406,17 @@ namespace Emby.Server.Implementations
SystemEvents = systemEvents;
ApplicationPaths = applicationPaths;
- LogManager = logManager;
+ LoggerFactory = loggerFactory;
FileSystemManager = fileSystem;
ConfigurationManager = GetConfigurationManager();
- // Initialize this early in case the -v command line option is used
- Logger = LogManager.GetLogger("App");
+ Logger = LoggerFactory.CreateLogger("App");
StartupOptions = options;
- ReleaseAssetFilename = releaseAssetFilename;
- PowerManagement = powerManagement;
ImageEncoder = imageEncoder;
- SetBaseExceptionMessage();
-
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
@@ -469,7 +457,7 @@ namespace Emby.Server.Implementations
{
get
{
- return _version ?? (_version = GetType().GetTypeInfo().Assembly.GetName().Version);
+ return _version ?? (_version = typeof(ApplicationHost).Assembly.GetName().Version);
}
}
@@ -480,7 +468,7 @@ namespace Emby.Server.Implementations
{
if (_deviceId == null)
{
- _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
+ _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger("SystemId"), FileSystemManager);
}
return _deviceId.Value;
@@ -512,14 +500,6 @@ namespace Emby.Server.Implementations
return new StreamHelper();
}
- public virtual bool SupportsAutoRunAtStartup
- {
- get
- {
- return EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
- }
- }
-
/// <summary>
/// Creates an instance of type and resolves all constructor dependancies
/// </summary>
@@ -545,7 +525,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error creating {0}", ex, type.FullName);
+ Logger.LogError(ex, "Error creating {type}", type.FullName);
// Don't blow up in release mode
return null;
}
@@ -625,7 +605,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading assembly {0}", ex, file);
+ Logger.LogError(ex, "Error loading assembly {file}", file);
return null;
}
}
@@ -646,17 +626,16 @@ namespace Emby.Server.Implementations
/// Gets the exports.
/// </summary>
/// <typeparam name="T"></typeparam>
- /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
+ /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
/// <returns>IEnumerable{``0}.</returns>
- public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
+ public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
{
var parts = GetExportTypes<T>()
.Select(CreateInstanceSafe)
.Where(i => i != null)
- .Cast<T>()
- .ToList();
+ .Cast<T>();
- if (manageLiftime)
+ if (manageLifetime)
{
lock (DisposableParts)
{
@@ -667,7 +646,7 @@ namespace Emby.Server.Implementations
return parts;
}
- public List<Tuple<T, string>> GetExportsWithInfo<T>(bool manageLiftime = true)
+ public List<Tuple<T, string>> GetExportsWithInfo<T>(bool manageLifetime = true)
{
var parts = GetExportTypes<T>()
.Select(i =>
@@ -683,7 +662,7 @@ namespace Emby.Server.Implementations
.Where(i => i != null)
.ToList();
- if (manageLiftime)
+ if (manageLifetime)
{
lock (DisposableParts)
{
@@ -694,25 +673,13 @@ namespace Emby.Server.Implementations
return parts;
}
- private void SetBaseExceptionMessage()
- {
- var builder = GetBaseExceptionMessage(ApplicationPaths);
-
- builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine));
- builder.Insert(0, "*** Error Report ***" + Environment.NewLine);
-
- LogManager.ExceptionMessagePrefix = builder.ToString();
- }
-
/// <summary>
/// Runs the startup tasks.
/// </summary>
- public async Task RunStartupTasks()
+ public Task RunStartupTasks()
{
Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
- ConfigureAutorun();
-
ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
MediaEncoder.Init();
@@ -726,20 +693,20 @@ namespace Emby.Server.Implementations
// }
//}
- Logger.Info("ServerId: {0}", SystemId);
+ Logger.LogInformation("ServerId: {0}", SystemId);
var entryPoints = GetExports<IServerEntryPoint>();
RunEntryPoints(entryPoints, true);
- Logger.Info("Core startup complete");
+ Logger.LogInformation("Core startup complete");
HttpServer.GlobalResponse = null;
- Logger.Info("Post-init migrations complete");
+ Logger.LogInformation("Post-init migrations complete");
RunEntryPoints(entryPoints, false);
- Logger.Info("All entry points have started");
+ Logger.LogInformation("All entry points have started");
- LogManager.RemoveConsoleOutput();
+ return Task.CompletedTask;
}
private void RunEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
@@ -752,7 +719,7 @@ namespace Emby.Server.Implementations
}
var name = entryPoint.GetType().FullName;
- Logger.Info("Starting entry point {0}", name);
+ Logger.LogInformation("Starting entry point {Name}", name);
var now = DateTime.UtcNow;
try
{
@@ -760,30 +727,15 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error in {0}", ex, name);
+ Logger.LogError(ex, "Error while running entrypoint {Name}", name);
}
- Logger.Info("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos");
- }
- }
-
- /// <summary>
- /// Configures the autorun.
- /// </summary>
- private void ConfigureAutorun()
- {
- try
- {
- ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error configuring autorun", ex);
+ Logger.LogInformation("Entry point completed: {Name}. Duration: {Duration} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos");
}
}
private IJsonSerializer CreateJsonSerializer()
{
- return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer"));
+ return new JsonSerializer(FileSystemManager, LoggerFactory.CreateLogger("JsonSerializer"));
}
public void Init()
@@ -800,31 +752,6 @@ namespace Emby.Server.Implementations
JsonSerializer = CreateJsonSerializer();
- OnLoggerLoaded(true);
- LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
-
- LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
- ? LogSeverity.Debug
- : LogSeverity.Info;
-
- DiscoverTypes();
-
- SetHttpLimit();
-
- RegisterResources();
-
- FindParts();
- }
-
- protected virtual void OnLoggerLoaded(bool isFirstLoad)
- {
- Logger.Info("Application version: {0}", ApplicationVersion);
-
- if (!isFirstLoad)
- {
- LogEnvironmentInfo(Logger, ApplicationPaths, false);
- }
-
if (Plugins != null)
{
var pluginBuilder = new StringBuilder();
@@ -834,13 +761,21 @@ namespace Emby.Server.Implementations
pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
}
- Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
+ Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
}
+
+ DiscoverTypes();
+
+ SetHttpLimit();
+
+ RegisterResources();
+
+ FindParts();
}
protected virtual IHttpClient CreateHttpClient()
{
- return new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent);
+ return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory.CreateLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent);
}
public static IStreamHelper StreamHelper { get; set; }
@@ -858,7 +793,7 @@ namespace Emby.Server.Implementations
RegisterSingleInstance(JsonSerializer);
RegisterSingleInstance(SystemEvents);
- RegisterSingleInstance(LogManager, false);
+ RegisterSingleInstance(LoggerFactory, false);
RegisterSingleInstance(Logger);
RegisterSingleInstance(EnvironmentInfo);
@@ -873,7 +808,7 @@ namespace Emby.Server.Implementations
IsoManager = new IsoManager();
RegisterSingleInstance(IsoManager);
- TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents);
+ TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory.CreateLogger("TaskManager"), FileSystemManager, SystemEvents);
RegisterSingleInstance(TaskManager);
RegisterSingleInstance(XmlSerializer);
@@ -890,21 +825,19 @@ namespace Emby.Server.Implementations
RegisterSingleInstance(CryptographyProvider);
- SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory"));
+ SocketFactory = new SocketFactory(LoggerFactory.CreateLogger("SocketFactory"));
RegisterSingleInstance(SocketFactory);
- RegisterSingleInstance(PowerManagement);
-
- SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager, FileSystemManager, CryptographyProvider);
+ SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LoggerFactory, FileSystemManager, CryptographyProvider);
RegisterSingleInstance(SecurityManager);
- InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime);
+ InstallationManager = new InstallationManager(LoggerFactory.CreateLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime);
RegisterSingleInstance(InstallationManager);
ZipClient = new ZipClient(FileSystemManager);
RegisterSingleInstance(ZipClient);
- HttpResultFactory = new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
+ HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
RegisterSingleInstance(HttpResultFactory);
RegisterSingleInstance<IServerApplicationHost>(this);
@@ -915,36 +848,36 @@ namespace Emby.Server.Implementations
IAssemblyInfo assemblyInfo = new AssemblyInfo();
RegisterSingleInstance<IAssemblyInfo>(assemblyInfo);
- LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LogManager.GetLogger("LocalizationManager"), assemblyInfo, new TextLocalizer());
+ LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory.CreateLogger("LocalizationManager"), assemblyInfo, new TextLocalizer());
StringExtensions.LocalizationManager = LocalizationManager;
RegisterSingleInstance(LocalizationManager);
- TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LogManager.GetLogger("TextEncoding"), JsonSerializer);
+ TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LoggerFactory.CreateLogger("TextEncoding"), JsonSerializer);
RegisterSingleInstance(TextEncoding);
BlurayExaminer = new BdInfoExaminer(FileSystemManager, TextEncoding);
RegisterSingleInstance(BlurayExaminer);
RegisterSingleInstance<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
- UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager, () => UserManager);
+ UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
RegisterSingleInstance(UserDataManager);
UserRepository = GetUserRepository();
// This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
RegisterSingleInstance(UserRepository);
- var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager.GetLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager);
+ var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory.CreateLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager);
DisplayPreferencesRepository = displayPreferencesRepo;
RegisterSingleInstance(DisplayPreferencesRepository);
- var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LogManager.GetLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory);
+ var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory.CreateLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory);
ItemRepository = itemRepo;
RegisterSingleInstance(ItemRepository);
AuthenticationRepository = GetAuthenticationRepository();
RegisterSingleInstance(AuthenticationRepository);
- UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider);
+ UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider);
RegisterSingleInstance(UserManager);
LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
@@ -953,16 +886,16 @@ namespace Emby.Server.Implementations
var musicManager = new MusicManager(LibraryManager);
RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
- LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo);
+ LibraryMonitor = new LibraryMonitor(LoggerFactory, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo);
RegisterSingleInstance(LibraryMonitor);
- RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
+ RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LoggerFactory, LibraryManager, UserManager));
CertificateInfo = GetCertificateInfo(true);
Certificate = GetCertificate(CertificateInfo);
HttpServer = new HttpListenerHost(this,
- LogManager.GetLogger("HttpServer"),
+ LoggerFactory.CreateLogger("HttpServer"),
ServerConfigurationManager,
"web/index.html",
NetworkManager,
@@ -983,37 +916,34 @@ namespace Emby.Server.Implementations
var encryptionManager = new EncryptionManager();
RegisterSingleInstance<IEncryptionManager>(encryptionManager);
- DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LogManager.GetLogger("DeviceManager"), NetworkManager);
+ DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager);
RegisterSingleInstance(DeviceManager);
- var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
- RegisterSingleInstance<INewsService>(newsService);
-
- MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LogManager.GetLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder);
+ MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder);
RegisterSingleInstance(MediaSourceManager);
- SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager);
+ SubtitleManager = new SubtitleManager(LoggerFactory.CreateLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager);
RegisterSingleInstance(SubtitleManager);
- ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
+ ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
RegisterSingleInstance(ProviderManager);
- DtoService = new DtoService(LogManager.GetLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
+ DtoService = new DtoService(LoggerFactory.CreateLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager);
RegisterSingleInstance(DtoService);
- ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LogManager.GetLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
+ ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory.CreateLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
RegisterSingleInstance(ChannelManager);
- SessionManager = new SessionManager(UserDataManager, LogManager.GetLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory);
+ SessionManager = new SessionManager(UserDataManager, LoggerFactory.CreateLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory);
RegisterSingleInstance(SessionManager);
- var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer, this, assemblyInfo);
+ var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory.CreateLogger("Dlna"), JsonSerializer, this, assemblyInfo);
RegisterSingleInstance<IDlnaManager>(dlnaManager);
- CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"), ProviderManager);
+ CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("CollectionManager"), ProviderManager);
RegisterSingleInstance(CollectionManager);
- PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager);
+ PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("PlaylistManager"), UserManager, ProviderManager);
RegisterSingleInstance<IPlaylistManager>(PlaylistManager);
LiveTvManager = new LiveTvManager(this, HttpClient, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager, () => ChannelManager);
@@ -1022,12 +952,12 @@ namespace Emby.Server.Implementations
UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
RegisterSingleInstance(UserViewManager);
- NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
+ NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
RegisterSingleInstance(NotificationManager);
- RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory));
+ RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LoggerFactory.CreateLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory));
- ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
+ ChapterManager = new ChapterManager(LibraryManager, LoggerFactory.CreateLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
RegisterSingleInstance(ChapterManager);
RegisterMediaEncoder(assemblyInfo);
@@ -1037,7 +967,7 @@ namespace Emby.Server.Implementations
var activityLogRepo = GetActivityLogRepository();
RegisterSingleInstance(activityLogRepo);
- RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
+ RegisterSingleInstance<IActivityManager>(new ActivityManager(LoggerFactory.CreateLogger("ActivityManager"), activityLogRepo, UserManager));
var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
RegisterSingleInstance<IAuthorizationContext>(authContext);
@@ -1046,14 +976,14 @@ namespace Emby.Server.Implementations
AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
RegisterSingleInstance<IAuthService>(AuthService);
- SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding);
+ SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory.CreateLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding);
RegisterSingleInstance(SubtitleEncoder);
RegisterSingleInstance(CreateResourceFileManager());
displayPreferencesRepo.Initialize();
- var userDataRepo = new SqliteUserDataRepository(LogManager.GetLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager);
+ var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager);
SetStaticProperties();
@@ -1078,47 +1008,25 @@ namespace Emby.Server.Implementations
{
get
{
- return "netframework";
+ return "netcore";
}
}
- public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
- {
- logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
- }
-
- protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
+ public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
{
- var builder = new StringBuilder();
-
// Distinct these to prevent users from reporting problems that aren't actually problems
var commandLineArgs = Environment
.GetCommandLineArgs()
- .Distinct()
- .ToArray();
-
- builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", commandLineArgs)));
-
- builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
- builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
- builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
- builder.AppendLine(string.Format("User Interactive: {0}", Environment.UserInteractive));
-
- Type type = Type.GetType("Mono.Runtime");
- if (type != null)
- {
- MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
- if (displayName != null)
- {
- builder.AppendLine("Mono: " + displayName.Invoke(null, null));
- }
- }
+ .Distinct();
- builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
- builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
- builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath));
-
- return builder;
+ logger.LogInformation("Arguments: {Args}", commandLineArgs);
+ logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
+ logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
+ logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
+ logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
+ logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
+ logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
+ logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
}
private void SetHttpLimit()
@@ -1130,7 +1038,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error setting http limit", ex);
+ Logger.LogError(ex, "Error setting http limit");
}
}
@@ -1189,7 +1097,7 @@ namespace Emby.Server.Implementations
//localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
if (!localCert.HasPrivateKey)
{
- Logger.Error("No private key included in SSL cert {0}.", certificateLocation);
+ Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
return null;
}
@@ -1197,14 +1105,14 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading cert from {0}", ex, certificateLocation);
+ Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
return null;
}
}
private IImageProcessor GetImageProcessor()
{
- return new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder);
+ return new ImageProcessor(LoggerFactory.CreateLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder);
}
protected virtual FFMpegInstallInfo GetFfmpegInstallInfo()
@@ -1262,7 +1170,8 @@ namespace Emby.Server.Implementations
probePath = info.ProbePath;
var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
- var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(LogManager.GetLogger("MediaEncoder"),
+ var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
+ LoggerFactory.CreateLogger("MediaEncoder"),
JsonSerializer,
encoderPath,
probePath,
@@ -1279,7 +1188,7 @@ namespace Emby.Server.Implementations
HttpClient,
ZipClient,
ProcessFactory,
- 5000, false,
+ 5000,
EnvironmentInfo);
MediaEncoder = mediaEncoder;
@@ -1292,7 +1201,7 @@ namespace Emby.Server.Implementations
/// <returns>Task{IUserRepository}.</returns>
private IUserRepository GetUserRepository()
{
- var repo = new SqliteUserRepository(LogManager.GetLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer);
+ var repo = new SqliteUserRepository(LoggerFactory.CreateLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer);
repo.Initialize();
@@ -1301,7 +1210,7 @@ namespace Emby.Server.Implementations
private IAuthenticationRepository GetAuthenticationRepository()
{
- var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager);
+ var repo = new AuthenticationRepository(LoggerFactory.CreateLogger("AuthenticationRepository"), ServerConfigurationManager);
repo.Initialize();
@@ -1310,7 +1219,7 @@ namespace Emby.Server.Implementations
private IActivityRepository GetActivityLogRepository()
{
- var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager);
+ var repo = new ActivityRepository(LoggerFactory.CreateLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager);
repo.Initialize();
@@ -1325,7 +1234,7 @@ namespace Emby.Server.Implementations
((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor;
// For now there's no real way to inject these properly
- BaseItem.Logger = LogManager.GetLogger("BaseItem");
+ BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
BaseItem.ConfigurationManager = ServerConfigurationManager;
BaseItem.LibraryManager = LibraryManager;
BaseItem.ProviderManager = ProviderManager;
@@ -1354,7 +1263,6 @@ namespace Emby.Server.Implementations
{
if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
{
- RegisterServerWithAdministratorAccess();
ServerConfigurationManager.Configuration.IsPortAuthorized = true;
ConfigurationManager.SaveConfiguration();
}
@@ -1425,19 +1333,18 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting plugin Id from {0}.", ex, plugin.GetType().FullName);
+ Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
}
}
- var hasPluginConfiguration = plugin as IHasPluginConfiguration;
- if (hasPluginConfiguration != null)
+ if (plugin is IHasPluginConfiguration hasPluginConfiguration)
{
hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
}
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
+ Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
return null;
}
@@ -1449,7 +1356,7 @@ namespace Emby.Server.Implementations
/// </summary>
protected void DiscoverTypes()
{
- Logger.Info("Loading assemblies");
+ Logger.LogInformation("Loading assemblies");
var assemblyInfos = GetComposablePartAssemblies();
@@ -1460,11 +1367,11 @@ namespace Emby.Server.Implementations
if (path == null)
{
- Logger.Info("Loading {0}", assembly.FullName);
+ Logger.LogInformation("Loading {assemblyName}", assembly.FullName);
}
else
{
- Logger.Info("Loading {0} from {1}", assembly.FullName, path);
+ Logger.LogInformation("Loading {assemblyName} from {path}", assembly.FullName, path);
}
}
@@ -1506,7 +1413,7 @@ namespace Emby.Server.Implementations
{
if (loaderException != null)
{
- Logger.Error("LoaderException: " + loaderException.Message);
+ Logger.LogError("LoaderException: " + loaderException.Message);
}
}
}
@@ -1517,7 +1424,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading types from assembly", ex);
+ Logger.LogError(ex, "Error loading types from assembly");
return new List<Tuple<Type, string>>();
}
@@ -1564,7 +1471,7 @@ namespace Emby.Server.Implementations
? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system."
: "Error starting Http Server";
- Logger.ErrorException(msg, ex);
+ Logger.LogError(ex, msg);
if (HttpPort == ServerConfiguration.DefaultHttpPort)
{
@@ -1580,7 +1487,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error starting http server", ex);
+ Logger.LogError(ex, "Error starting http server");
throw;
}
@@ -1615,7 +1522,7 @@ namespace Emby.Server.Implementations
// }
// catch (Exception ex)
// {
- // Logger.ErrorException("Error creating ssl cert", ex);
+ // Logger.LogError(ex, "Error creating ssl cert");
// return null;
// }
// }
@@ -1635,8 +1542,6 @@ namespace Emby.Server.Implementations
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void OnConfigurationUpdated(object sender, EventArgs e)
{
- ConfigureAutorun();
-
var requiresRestart = false;
// Don't do anything if these haven't been set yet
@@ -1672,7 +1577,7 @@ namespace Emby.Server.Implementations
if (requiresRestart)
{
- Logger.Info("App needs to be restarted due to configuration change.");
+ Logger.LogInformation("App needs to be restarted due to configuration change.");
NotifyPendingRestart();
}
@@ -1683,7 +1588,7 @@ namespace Emby.Server.Implementations
/// </summary>
public void NotifyPendingRestart()
{
- Logger.Info("App needs to be restarted.");
+ Logger.LogInformation("App needs to be restarted.");
var changed = !HasPendingRestart;
@@ -1720,10 +1625,10 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error sending server restart notification", ex);
+ Logger.LogError(ex, "Error sending server restart notification");
}
- Logger.Info("Calling RestartInternal");
+ Logger.LogInformation("Calling RestartInternal");
RestartInternal();
});
@@ -1786,7 +1691,7 @@ namespace Emby.Server.Implementations
return list.ToList();
}
- protected abstract List<Assembly> GetAssembliesWithPartsInternal();
+ protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
/// <summary>
/// Gets the plugin assemblies.
@@ -1849,13 +1754,13 @@ namespace Emby.Server.Implementations
{
var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
- Logger.Info("File {0} has version {1}", path, result);
+ Logger.LogInformation("File {Path} has version {Version}", path, result);
return result;
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting version number from {0}", ex, path);
+ Logger.LogError(ex, "Error getting version number from {Path}", path);
return new Version(1, 0);
}
@@ -1940,13 +1845,13 @@ namespace Emby.Server.Implementations
if (version < minRequiredVersion)
{
- Logger.Info("Not loading {0} {1} because the minimum supported version is {2}. Please update to the newer version", filename, version, minRequiredVersion);
+ Logger.LogInformation("Not loading {filename} {version} because the minimum supported version is {minRequiredVersion}. Please update to the newer version", filename, version, minRequiredVersion);
return false;
}
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting version number from {0}", ex, path);
+ Logger.LogError(ex, "Error getting version number from {path}", path);
return false;
}
@@ -1987,7 +1892,6 @@ namespace Emby.Server.Implementations
CanLaunchWebBrowser = CanLaunchWebBrowser,
WanAddress = wanAddress,
HasUpdateAvailable = HasUpdateAvailable,
- SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
ServerName = FriendlyName,
LocalAddress = localAddress,
@@ -2053,7 +1957,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting local Ip address information", ex);
+ Logger.LogError(ex, "Error getting local Ip address information");
}
return null;
@@ -2080,7 +1984,7 @@ namespace Emby.Server.Implementations
}
catch(Exception ex)
{
- Logger.ErrorException("Error getting WAN Ip address information", ex);
+ Logger.LogError(ex, "Error getting WAN Ip address information");
}
return null;
}
@@ -2210,19 +2114,19 @@ namespace Emby.Server.Implementations
var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
_validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
- Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, valid);
+ Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
return valid;
}
}
}
catch (OperationCanceledException)
{
- Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
+ Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
throw;
}
catch (Exception ex)
{
- Logger.Debug("Ping test result to {0}. Success: {1} {2}", apiUrl, false, ex.Message);
+ Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
_validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
return false;
@@ -2261,7 +2165,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error sending server shutdown notification", ex);
+ Logger.LogError(ex, "Error sending server shutdown notification");
}
ShutdownInternal();
@@ -2269,32 +2173,6 @@ namespace Emby.Server.Implementations
protected abstract void ShutdownInternal();
- /// <summary>
- /// Registers the server with administrator access.
- /// </summary>
- private void RegisterServerWithAdministratorAccess()
- {
- Logger.Info("Requesting administrative access to authorize http server");
-
- try
- {
- AuthorizeServer();
- }
- catch (NotImplementedException)
- {
-
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error authorizing server", ex);
- }
- }
-
- protected virtual void AuthorizeServer()
- {
- throw new NotImplementedException();
- }
-
public event EventHandler HasUpdateAvailableChanged;
private bool _hasUpdateAvailable;
@@ -2309,7 +2187,7 @@ namespace Emby.Server.Implementations
if (fireEvent)
{
- EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
+ HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
}
}
}
@@ -2326,56 +2204,6 @@ namespace Emby.Server.Implementations
}
/// <summary>
- /// Checks for update.
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="progress">The progress.</param>
- /// <returns>Task{CheckForUpdateResult}.</returns>
- public async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
- {
- var updateLevel = SystemUpdateLevel;
- var cacheLength = updateLevel == PackageVersionClass.Release ?
- TimeSpan.FromHours(12) :
- TimeSpan.FromMinutes(5);
-
- try
- {
- var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser",
- "Emby.Releases",
- ApplicationVersion,
- updateLevel,
- ReleaseAssetFilename,
- "MBServer",
- UpdateTargetFileName,
- cacheLength,
- cancellationToken).ConfigureAwait(false);
-
- HasUpdateAvailable = result.IsUpdateAvailable;
-
- return result;
- }
- catch (HttpException ex)
- {
- // users are overreacting to this occasionally failing
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.Forbidden)
- {
- HasUpdateAvailable = false;
- return new CheckForUpdateResult
- {
- IsUpdateAvailable = false
- };
- }
-
- throw;
- }
- }
-
- protected virtual string UpdateTargetFileName
- {
- get { return "Mbserver.zip"; }
- }
-
- /// <summary>
/// Updates the application.
/// </summary>
/// <param name="package">The package that contains the update</param>
@@ -2391,23 +2219,6 @@ namespace Emby.Server.Implementations
}
/// <summary>
- /// Configures the automatic run at startup.
- /// </summary>
- /// <param name="autorun">if set to <c>true</c> [autorun].</param>
- protected void ConfigureAutoRunAtStartup(bool autorun)
- {
- if (SupportsAutoRunAtStartup)
- {
- ConfigureAutoRunInternal(autorun);
- }
- }
-
- protected virtual void ConfigureAutoRunInternal(bool autorun)
- {
- throw new NotImplementedException();
- }
-
- /// <summary>
/// This returns localhost in the case of no external dns, and the hostname if the
/// dns is prefixed with a valid Uri prefix.
/// </summary>
@@ -2453,9 +2264,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Console.WriteLine("Error launching url: {0}", url);
- Logger.ErrorException("Error launching url: {0}", ex, url);
-
+ Logger.LogError(ex, "Error launching url: {url}", url);
throw;
}
}
@@ -2475,13 +2284,12 @@ namespace Emby.Server.Implementations
/// <param name="package">The package.</param>
protected void OnApplicationUpdated(PackageVersionInfo package)
{
- Logger.Info("Application has been updated to version {0}", package.versionStr);
+ Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
- EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
+ ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
{
Argument = package
-
- }, Logger);
+ });
NotifyPendingRestart();
}
@@ -2510,15 +2318,14 @@ namespace Emby.Server.Implementations
{
var type = GetType();
- LogManager.AddConsoleOutput();
- Logger.Info("Disposing " + type.Name);
+ Logger.LogInformation("Disposing {Type}", type.Name);
var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
DisposableParts.Clear();
foreach (var part in parts)
{
- Logger.Info("Disposing " + part.GetType().Name);
+ Logger.LogInformation("Disposing {Type}", part.GetType().Name);
try
{
@@ -2526,58 +2333,11 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
+ Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
}
}
}
}
-
- private Dictionary<string, string> _values;
- public string GetValue(string name)
- {
- if (_values == null)
- {
- _values = LoadValues();
- }
-
- string value;
-
- if (_values.TryGetValue(name, out value))
- {
- return value;
- }
-
- return null;
- }
-
- // TODO: @bond Remove?
- private Dictionary<string, string> LoadValues()
- {
- Dictionary<string, string> values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- using (var stream = typeof(ApplicationHost).Assembly.GetManifestResourceStream(typeof(ApplicationHost).Namespace + ".values.txt"))
- {
- using (var reader = new StreamReader(stream))
- {
- while (!reader.EndOfStream)
- {
- var line = reader.ReadLine();
- if (string.IsNullOrEmpty(line))
- {
- continue;
- }
-
- var index = line.IndexOf('=');
- if (index != -1)
- {
- values[line.Substring(0, index)] = line.Substring(index + 1);
- }
- }
- }
- }
-
- return values;
- }
}
internal class CertificateInfo
diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs
index dfc9c3474..c2160d338 100644
--- a/Emby.Server.Implementations/Channels/ChannelManager.cs
+++ b/Emby.Server.Implementations/Channels/ChannelManager.cs
@@ -10,7 +10,7 @@ using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
@@ -300,7 +300,7 @@ namespace Emby.Server.Implementations.Channels
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name);
+ _logger.LogError(ex, "Error getting channel information for {0}", channelInfo.Name);
}
numComplete++;
@@ -484,10 +484,9 @@ namespace Emby.Server.Implementations.Channels
_libraryManager.CreateItem(item, null);
}
- await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
+ await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ForceSave = !isNew && forceUpdate
-
}, cancellationToken);
return item;
@@ -709,7 +708,7 @@ namespace Emby.Server.Implementations.Channels
// Not yet sure why this is causing a problem
query.GroupByPresentationUniqueKey = false;
- //_logger.Debug("GetChannelItemsInternal");
+ //_logger.LogDebug("GetChannelItemsInternal");
// null if came from cache
if (itemsResult != null)
@@ -849,7 +848,7 @@ namespace Emby.Server.Implementations.Channels
}
catch (Exception ex)
{
- _logger.ErrorException("Error writing to channel cache file: {0}", ex, path);
+ _logger.LogError(ex, "Error writing to channel cache file: {path}", path);
}
}
@@ -902,8 +901,8 @@ namespace Emby.Server.Implementations.Channels
private T GetItemById<T>(string idString, string channelName, out bool isNew)
where T : BaseItem, new()
{
- var id = GetIdToHash(idString, channelName).GetMBId(typeof(T));
-
+ var id = _libraryManager.GetNewItemId(GetIdToHash(idString, channelName), typeof(T));
+
T item = null;
try
@@ -912,7 +911,7 @@ namespace Emby.Server.Implementations.Channels
}
catch (Exception ex)
{
- _logger.ErrorException("Error retrieving channel item from database", ex);
+ _logger.LogError(ex, "Error retrieving channel item from database");
}
if (item == null)
@@ -1051,7 +1050,7 @@ namespace Emby.Server.Implementations.Channels
{
if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes))
{
- _logger.Debug("Forcing update due to TrailerTypes {0}", item.Name);
+ _logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name);
forceUpdate = true;
}
trailer.TrailerTypes = info.TrailerTypes.ToArray();
@@ -1060,7 +1059,7 @@ namespace Emby.Server.Implementations.Channels
if (info.DateModified > item.DateModified)
{
item.DateModified = info.DateModified;
- _logger.Debug("Forcing update due to DateModified {0}", item.Name);
+ _logger.LogDebug("Forcing update due to DateModified {0}", item.Name);
forceUpdate = true;
}
@@ -1069,20 +1068,20 @@ namespace Emby.Server.Implementations.Channels
//{
// item.ExternalEtag = info.Etag;
// forceUpdate = true;
- // _logger.Debug("Forcing update due to ExternalEtag {0}", item.Name);
+ // _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name);
//}
if (!internalChannelId.Equals(item.ChannelId))
{
forceUpdate = true;
- _logger.Debug("Forcing update due to ChannelId {0}", item.Name);
+ _logger.LogDebug("Forcing update due to ChannelId {0}", item.Name);
}
item.ChannelId = internalChannelId;
if (!item.ParentId.Equals(parentFolderId))
{
forceUpdate = true;
- _logger.Debug("Forcing update due to parent folder Id {0}", item.Name);
+ _logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name);
}
item.ParentId = parentFolderId;
@@ -1092,7 +1091,7 @@ namespace Emby.Server.Implementations.Channels
if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase))
{
forceUpdate = true;
- _logger.Debug("Forcing update due to SeriesName {0}", item.Name);
+ _logger.LogDebug("Forcing update due to SeriesName {0}", item.Name);
}
hasSeries.SeriesName = info.SeriesName;
}
@@ -1100,7 +1099,7 @@ namespace Emby.Server.Implementations.Channels
if (!string.Equals(item.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase))
{
forceUpdate = true;
- _logger.Debug("Forcing update due to ExternalId {0}", item.Name);
+ _logger.LogDebug("Forcing update due to ExternalId {0}", item.Name);
}
item.ExternalId = info.Id;
@@ -1125,7 +1124,7 @@ namespace Emby.Server.Implementations.Channels
if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary))
{
item.SetImagePath(ImageType.Primary, info.ImageUrl);
- _logger.Debug("Forcing update due to ImageUrl {0}", item.Name);
+ _logger.LogDebug("Forcing update due to ImageUrl {0}", item.Name);
forceUpdate = true;
}
@@ -1134,7 +1133,7 @@ namespace Emby.Server.Implementations.Channels
if (item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
{
item.Tags = item.Tags.Except(new[] { "livestream" }, StringComparer.OrdinalIgnoreCase).ToArray();
- _logger.Debug("Forcing update due to Tags {0}", item.Name);
+ _logger.LogDebug("Forcing update due to Tags {0}", item.Name);
forceUpdate = true;
}
}
@@ -1143,7 +1142,7 @@ namespace Emby.Server.Implementations.Channels
if (!item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
{
item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray();
- _logger.Debug("Forcing update due to Tags {0}", item.Name);
+ _logger.LogDebug("Forcing update due to Tags {0}", item.Name);
forceUpdate = true;
}
}
@@ -1178,7 +1177,7 @@ namespace Emby.Server.Implementations.Channels
if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime))
{
- _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal);
+ _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal);
}
return item;
diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
index b211908d8..bd717bc6a 100644
--- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
+++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Channels
private void CleanChannel(Guid id, CancellationToken cancellationToken)
{
- _logger.Info("Cleaning channel {0} from database", id);
+ _logger.LogInformation("Cleaning channel {0} from database", id);
// Delete all channel items
var allIds = _libraryManager.GetItemIds(new InternalItemsQuery
diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
index 020818361..ab6acf3c5 100644
--- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
+++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
@@ -1,8 +1,9 @@
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
+using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Tasks;
@@ -54,7 +55,7 @@ namespace Emby.Server.Implementations.Channels
get { return true; }
}
- public async Task Execute(System.Threading.CancellationToken cancellationToken, IProgress<double> progress)
+ public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
var manager = (ChannelManager)_channelManager;
diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs
index bcfc58ca1..d1d793136 100644
--- a/Emby.Server.Implementations/Collections/CollectionManager.cs
+++ b/Emby.Server.Implementations/Collections/CollectionManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.Collections
if (options.ItemIdList.Length > 0)
{
- AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(_fileSystem)
+ AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// The initial adding of items is going to create a local metadata file
// This will cause internet metadata to be skipped as a result
@@ -152,15 +152,14 @@ namespace Emby.Server.Implementations.Collections
}
else
{
- _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High);
+ _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High);
}
- EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs
+ CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
{
Collection = collection,
Options = options
-
- }, _logger);
+ });
return collection;
}
@@ -173,12 +172,12 @@ namespace Emby.Server.Implementations.Collections
public void AddToCollection(Guid collectionId, IEnumerable<string> ids)
{
- AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(_fileSystem));
+ AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
}
public void AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
{
- AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(_fileSystem));
+ AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
}
private void AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
@@ -230,12 +229,11 @@ namespace Emby.Server.Implementations.Collections
if (fireEvent)
{
- EventHelper.FireEventIfNotNull(ItemsAddedToCollection, this, new CollectionModifiedEventArgs
+ ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
{
Collection = collection,
ItemsChanged = itemList
-
- }, _logger);
+ });
}
}
}
@@ -265,7 +263,7 @@ namespace Emby.Server.Implementations.Collections
if (child == null)
{
- _logger.Warn("No collection title exists with the supplied Id");
+ _logger.LogWarning("No collection title exists with the supplied Id");
continue;
}
@@ -283,17 +281,16 @@ namespace Emby.Server.Implementations.Collections
}
collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
- _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ForceSave = true
}, RefreshPriority.High);
- EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
+ ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
{
Collection = collection,
ItemsChanged = itemList
-
- }, _logger);
+ });
}
public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
@@ -365,7 +362,7 @@ namespace Emby.Server.Implementations.Collections
}
catch (Exception ex)
{
- _logger.ErrorException("Error creating camera uploads library", ex);
+ _logger.LogError(ex, "Error creating camera uploads library");
}
_config.Configuration.CollectionsUpgraded = true;
diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
index 47e2ec0a8..015421197 100644
--- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
+++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
@@ -1,22 +1,15 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using Emby.Server.Implementations.AppBase;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Events;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Configuration
{
@@ -30,11 +23,11 @@ namespace Emby.Server.Implementations.Configuration
/// Initializes a new instance of the <see cref="ServerConfigurationManager" /> class.
/// </summary>
/// <param name="applicationPaths">The application paths.</param>
- /// <param name="logManager">The log manager.</param>
+ /// <param name="loggerFactory">The paramref name="loggerFactory" factory.</param>
/// <param name="xmlSerializer">The XML serializer.</param>
/// <param name="fileSystem">The file system.</param>
- public ServerConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
- : base(applicationPaths, logManager, xmlSerializer, fileSystem)
+ public ServerConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
+ : base(applicationPaths, loggerFactory, xmlSerializer, fileSystem)
{
UpdateMetadataPath();
}
@@ -143,7 +136,7 @@ namespace Emby.Server.Implementations.Configuration
ValidateMetadataPath(newConfig);
ValidateSslCertificate(newConfig);
- EventHelper.FireEventIfNotNull(ConfigurationUpdating, this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig }, Logger);
+ ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig });
base.ReplaceConfiguration(newConfiguration);
}
diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
index 76ebff3a8..59776c373 100644
--- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
+++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
using System.Linq;
using SQLitePCL;
@@ -75,22 +75,22 @@ namespace Emby.Server.Implementations.Data
if (!_versionLogged)
{
_versionLogged = true;
- Logger.Info("Sqlite version: " + SQLite3.Version);
- Logger.Info("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray()));
+ Logger.LogInformation("Sqlite version: " + SQLite3.Version);
+ Logger.LogInformation("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray()));
}
ConnectionFlags connectionFlags;
if (isReadOnly)
{
- //Logger.Info("Opening read connection");
+ //Logger.LogInformation("Opening read connection");
//connectionFlags = ConnectionFlags.ReadOnly;
connectionFlags = ConnectionFlags.Create;
connectionFlags |= ConnectionFlags.ReadWrite;
}
else
{
- //Logger.Info("Opening write connection");
+ //Logger.LogInformation("Opening write connection");
connectionFlags = ConnectionFlags.Create;
connectionFlags |= ConnectionFlags.ReadWrite;
}
@@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.Data
{
_defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
- Logger.Info("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
+ Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
}
var queries = new List<string>
@@ -235,7 +235,7 @@ namespace Emby.Server.Implementations.Data
}
db.ExecuteAll(string.Join(";", queries.ToArray()));
- Logger.Info("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
+ Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
}
protected virtual bool EnableTempStoreMemory
@@ -323,7 +323,7 @@ namespace Emby.Server.Implementations.Data
}
catch (Exception ex)
{
- Logger.ErrorException("Error disposing database", ex);
+ Logger.LogError(ex, "Error disposing database");
}
}
diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
index 8611cabc1..536cf21f6 100644
--- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
+++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Data
var numComplete = 0;
var numItems = itemIds.Count;
- _logger.Debug("Cleaning {0} items with dead parent links", numItems);
+ _logger.LogDebug("Cleaning {0} items with dead parent links", numItems);
foreach (var itemId in itemIds)
{
@@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Data
if (item != null)
{
- _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
+ _logger.LogInformation("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
_libraryManager.DeleteItem(item, new DeleteOptions
{
@@ -75,4 +75,4 @@ namespace Emby.Server.Implementations.Data
progress.Report(100);
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
index 09ff7e09d..00e1956cf 100644
--- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using SQLitePCL.pretty;
@@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.Data
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading database file. Will reset and retry.", ex);
+ Logger.LogError(ex, "Error loading database file. Will reset and retry.");
FileSystem.DeleteFile(DbFilePath);
@@ -251,4 +251,4 @@ namespace Emby.Server.Implementations.Data
return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
index 50cd69304..0f9770e8f 100644
--- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
@@ -24,7 +24,7 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Reflection;
@@ -667,7 +667,7 @@ namespace Emby.Server.Implementations.Data
var userDataKey = tuple.Item4;
SaveItem(item, topParent, userDataKey, saveItemStatement);
- //Logger.Debug(_saveItemCommand.CommandText);
+ //logger.LogDebug(_saveItemCommand.CommandText);
var inheritedTags = tuple.Item5;
@@ -886,12 +886,12 @@ namespace Emby.Server.Implementations.Data
if (topParent != null)
{
- //Logger.Debug("Item {0} has top parent {1}", item.Id, topParent.Id);
+ //logger.LogDebug("Item {0} has top parent {1}", item.Id, topParent.Id);
saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N"));
}
else
{
- //Logger.Debug("Item {0} has null top parent", item.Id);
+ //logger.LogDebug("Item {0} has null top parent", item.Id);
saveItemStatement.TryBindNull("@TopParentId");
}
@@ -1230,7 +1230,7 @@ namespace Emby.Server.Implementations.Data
}
CheckDisposed();
- //Logger.Info("Retrieving item {0}", id.ToString("N"));
+ //logger.LogInformation("Retrieving item {0}", id.ToString("N"));
using (WriteLock.Read())
{
using (var connection = CreateConnection(true))
@@ -1345,7 +1345,7 @@ namespace Emby.Server.Implementations.Data
if (type == null)
{
- //Logger.Debug("Unknown type {0}", typeString);
+ //logger.LogDebug("Unknown type {0}", typeString);
return null;
}
@@ -1364,7 +1364,7 @@ namespace Emby.Server.Implementations.Data
}
catch (SerializationException ex)
{
- Logger.ErrorException("Error deserializing item", ex);
+ Logger.LogError(ex, "Error deserializing item");
}
}
}
@@ -2686,7 +2686,7 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
- //Logger.Info("GetItemList: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -2744,7 +2744,7 @@ namespace Emby.Server.Implementations.Data
CheckDisposed();
- //Logger.Info("GetItemList: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -2910,14 +2910,14 @@ namespace Emby.Server.Implementations.Data
if (elapsed >= slowThreshold)
{
- Logger.Debug("{2} query time (slow): {0}ms. Query: {1}",
+ Logger.LogDebug("{2} query time (slow): {0}ms. Query: {1}",
Convert.ToInt32(elapsed),
commandText,
methodName);
}
else
{
- //Logger.Debug("{2} query time: {0}ms. Query: {1}",
+ //logger.LogDebug("{2} query time: {0}ms. Query: {1}",
// Convert.ToInt32(elapsed),
// commandText,
// methodName);
@@ -2942,7 +2942,7 @@ namespace Emby.Server.Implementations.Data
TotalRecordCount = returnList.Count
};
}
- //Logger.Info("GetItems: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItems: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -3216,7 +3216,7 @@ namespace Emby.Server.Implementations.Data
}
CheckDisposed();
- //Logger.Info("GetItemIdsList: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItemIdsList: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -3376,7 +3376,7 @@ namespace Emby.Server.Implementations.Data
TotalRecordCount = returnList.Count
};
}
- //Logger.Info("GetItemIds: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItemIds: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -5565,7 +5565,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
}
CheckDisposed();
- //Logger.Info("GetItemValues: " + _environmentInfo.StackTrace);
+ //logger.LogInformation("GetItemValues: " + _environmentInfo.StackTrace);
var now = DateTime.UtcNow;
@@ -5734,7 +5734,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
var list = new List<Tuple<BaseItem, ItemCounts>>();
var result = new QueryResult<Tuple<BaseItem, ItemCounts>>();
- //Logger.Info("GetItemValues {0}", string.Join(";", statementTexts.ToArray()));
+ //logger.LogInformation("GetItemValues {0}", string.Join(";", statementTexts.ToArray()));
var statements = PrepareAllSafe(db, statementTexts);
if (!isReturningZeroItems)
diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
index 07d64a2b0..6d4ddcedd 100644
--- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
using MediaBrowser.Controller.Library;
@@ -416,4 +416,4 @@ namespace Emby.Server.Implementations.Data
// handled by library database
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
index da828aa11..d490a481e 100644
--- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using SQLitePCL.pretty;
@@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.Data
}
catch (Exception ex)
{
- Logger.ErrorException("Error migrating users database", ex);
+ Logger.LogError(ex, "Error migrating users database");
}
}
@@ -233,4 +233,4 @@ namespace Emby.Server.Implementations.Data
}
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs
index 5e0323ddb..90cef5d06 100644
--- a/Emby.Server.Implementations/Devices/DeviceId.cs
+++ b/Emby.Server.Implementations/Devices/DeviceId.cs
@@ -3,7 +3,7 @@ using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Devices
{
@@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Devices
return value;
}
- _logger.Error("Invalid value found in device id file");
+ _logger.LogError("Invalid value found in device id file");
}
}
catch (DirectoryNotFoundException)
@@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.Devices
}
catch (Exception ex)
{
- _logger.ErrorException("Error reading file", ex);
+ _logger.LogError(ex, "Error reading file");
}
return null;
@@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.Devices
}
catch (Exception ex)
{
- _logger.ErrorException("Error writing to file", ex);
+ _logger.LogError(ex, "Error writing to file");
}
}
diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs
index 5c84590ae..f5314df6e 100644
--- a/Emby.Server.Implementations/Devices/DeviceManager.cs
+++ b/Emby.Server.Implementations/Devices/DeviceManager.cs
@@ -1,12 +1,11 @@
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Events;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Session;
@@ -145,7 +144,8 @@ namespace Emby.Server.Implementations.Devices
HasUser = true
}).Items;
-
+
+ // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
if (query.SupportsSync.HasValue)
{
var val = query.SupportsSync.Value;
@@ -253,14 +253,14 @@ namespace Emby.Server.Implementations.Devices
if (CameraImageUploaded != null)
{
- EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
+ CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
{
Argument = new CameraImageUploadInfo
{
Device = device,
FileInfo = file
}
- }, _logger);
+ });
}
}
@@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.Devices
}
catch (Exception ex)
{
- _logger.ErrorException("Error creating camera uploads library", ex);
+ _logger.LogError(ex, "Error creating camera uploads library");
}
_config.Configuration.CameraUploadUpgraded = true;
diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs
index 0831b1075..7871d3fb3 100644
--- a/Emby.Server.Implementations/Dto/DtoService.cs
+++ b/Emby.Server.Implementations/Dto/DtoService.cs
@@ -16,7 +16,7 @@ using MediaBrowser.Controller.Sync;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
@@ -225,7 +225,7 @@ namespace Emby.Server.Implementations.Dto
catch (Exception ex)
{
// Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
- _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
+ _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {itemName}", item.Name);
}
}
@@ -547,7 +547,7 @@ namespace Emby.Server.Implementations.Dto
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting {0} image info", ex, type);
+ _logger.LogError(ex, "Error getting {type} image info", type);
return null;
}
}
@@ -560,7 +560,7 @@ namespace Emby.Server.Implementations.Dto
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
+ _logger.LogError(ex, "Error getting {imageType} image info for {path}", image.Type, image.Path);
return null;
}
}
@@ -619,7 +619,7 @@ namespace Emby.Server.Implementations.Dto
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting person {0}", ex, c);
+ _logger.LogError(ex, "Error getting person {Name}", c);
return null;
}
@@ -1451,7 +1451,7 @@ namespace Emby.Server.Implementations.Dto
}
catch (Exception ex)
{
- //_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path);
+ _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
return null;
}
}
@@ -1464,7 +1464,7 @@ namespace Emby.Server.Implementations.Dto
}
catch (Exception ex)
{
- _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
+ _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name);
}
}
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index bf459defb..241505019 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -38,7 +38,7 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
- <ItemGroup>
+ <ItemGroup>
<EmbeddedResource Include="Localization\iso6392.txt" />
<EmbeddedResource Include="Localization\countries.json" />
<EmbeddedResource Include="Localization\Core\*.json" />
@@ -46,6 +46,6 @@
<EmbeddedResource Include="TextEncoding\NLangDetect\Utils\messages.properties" />
<EmbeddedResource Include="Localization\Ratings\*.txt" />
<EmbeddedResource Include="values.txt" />
- </ItemGroup>
+ </ItemGroup>
</Project>
diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs
index 561f5ee12..a0947c87d 100644
--- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs
+++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
using System;
using System.Linq;
@@ -65,7 +65,7 @@ namespace Emby.Server.Implementations.EntryPoints
{
DisposeTimer();
- _logger.Info("Automatically restarting the system because it is idle and a restart is required.");
+ _logger.LogInformation("Automatically restarting the system because it is idle and a restart is required.");
try
{
@@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error restarting server", ex);
+ _logger.LogError(ex, "Error restarting server");
}
}
}
@@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting timers", ex);
+ _logger.LogError(ex, "Error getting timers");
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index aa672a1b7..6cd867921 100644
--- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Threading;
using Mono.Nat;
using System.Threading;
@@ -29,9 +29,9 @@ namespace Emby.Server.Implementations.EntryPoints
private NatManager _natManager;
- public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory)
+ public ExternalPortForwarding(ILoggerFactory loggerFactory, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory)
{
- _logger = logmanager.GetLogger("PortMapper");
+ _logger = loggerFactory.CreateLogger("PortMapper");
_appHost = appHost;
_config = config;
_deviceDiscovery = deviceDiscovery;
@@ -84,7 +84,7 @@ namespace Emby.Server.Implementations.EntryPoints
private void Start()
{
- _logger.Debug("Starting NAT discovery");
+ _logger.LogDebug("Starting NAT discovery");
if (_natManager == null)
{
_natManager = new NatManager(_logger, _httpClient);
@@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.EntryPoints
_usnsHandled.Add(identifier);
}
- _logger.Debug("Found NAT device: " + identifier);
+ _logger.LogDebug("Found NAT device: " + identifier);
IPAddress address;
if (IPAddress.TryParse(info.Location.Host, out address))
@@ -166,6 +166,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
return;
}
@@ -216,7 +217,7 @@ namespace Emby.Server.Implementations.EntryPoints
catch
{
// Commenting out because users are reporting problems out of our control
- //_logger.ErrorException("Error creating port forwarding rules", ex);
+ //_logger.LogError(ex, "Error creating port forwarding rules");
}
}
@@ -253,6 +254,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error creating http port map");
return;
}
@@ -262,12 +264,13 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error creating https port map");
}
}
private Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
{
- _logger.Debug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString());
+ _logger.LogDebug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString());
return device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
{
@@ -284,7 +287,7 @@ namespace Emby.Server.Implementations.EntryPoints
private void DisposeNat()
{
- _logger.Debug("Stopping NAT discovery");
+ _logger.LogDebug("Stopping NAT discovery");
if (_timer != null)
{
@@ -309,7 +312,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error stopping NAT Discovery", ex);
+ _logger.LogError(ex, "Error stopping NAT Discovery");
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs
deleted file mode 100644
index 8ae85e390..000000000
--- a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
-using System;
-using System.Linq;
-using MediaBrowser.Model.System;
-using MediaBrowser.Model.Threading;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- public class KeepServerAwake : IServerEntryPoint
- {
- private readonly ISessionManager _sessionManager;
- private readonly ILogger _logger;
- private ITimer _timer;
- private readonly IServerApplicationHost _appHost;
- private readonly ITimerFactory _timerFactory;
- private readonly IPowerManagement _powerManagement;
-
- public KeepServerAwake(ISessionManager sessionManager, ILogger logger, IServerApplicationHost appHost, ITimerFactory timerFactory, IPowerManagement powerManagement)
- {
- _sessionManager = sessionManager;
- _logger = logger;
- _appHost = appHost;
- _timerFactory = timerFactory;
- _powerManagement = powerManagement;
- }
-
- public void Run()
- {
- _timer = _timerFactory.Create(OnTimerCallback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
- }
-
- private void OnTimerCallback(object state)
- {
- var now = DateTime.UtcNow;
-
- try
- {
- if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15))
- {
- _powerManagement.PreventSystemStandby();
- }
- else
- {
- _powerManagement.AllowSystemStandby();
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error resetting system standby timer", ex);
- }
- }
-
- public void Dispose()
- {
- if (_timer != null)
- {
- _timer.Dispose();
- _timer = null;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
index 9a2ae34bc..bb8ef52f1 100644
--- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -331,7 +331,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error in GetLibraryUpdateInfo", ex);
+ _logger.LogError(ex, "Error in GetLibraryUpdateInfo");
return;
}
@@ -346,7 +346,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending LibraryChanged message", ex);
+ _logger.LogError(ex, "Error sending LibraryChanged message");
}
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
index d41d76c6b..0b377dc68 100644
--- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
@@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message", ex);
+ _logger.LogError(ex, "Error sending message");
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
index 4c16b1d39..660ca3a94 100644
--- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
+++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
@@ -7,6 +7,7 @@ using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
@@ -15,10 +16,12 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILogger _logger;
/// <summary>
/// The _user manager
/// </summary>
private readonly IUserManager _userManager;
+
private IFileSystem _fileSystem;
public string Name => "Refresh Users";
@@ -41,8 +44,9 @@ namespace Emby.Server.Implementations.EntryPoints
/// <summary>
/// Initializes a new instance of the <see cref="RefreshUsersMetadata" /> class.
/// </summary>
- public RefreshUsersMetadata(IUserManager userManager, IFileSystem fileSystem)
+ public RefreshUsersMetadata(ILogger logger, IUserManager userManager, IFileSystem fileSystem)
{
+ _logger = logger;
_userManager = userManager;
_fileSystem = fileSystem;
}
@@ -55,7 +59,7 @@ namespace Emby.Server.Implementations.EntryPoints
{
cancellationToken.ThrowIfCancellationRequested();
- await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
+ await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
index e5748989e..72dcabab3 100644
--- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
@@ -157,13 +157,9 @@ namespace Emby.Server.Implementations.EntryPoints
{
await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None);
}
- catch (ObjectDisposedException)
- {
-
- }
catch (Exception)
{
- //Logger.ErrorException("Error sending message", ex);
+
}
}
@@ -173,13 +169,9 @@ namespace Emby.Server.Implementations.EntryPoints
{
await _sessionManager.SendMessageToUserSessions(new List<Guid> { user.Id }, name, data, CancellationToken.None);
}
- catch (ObjectDisposedException)
- {
-
- }
catch (Exception)
{
- //Logger.ErrorException("Error sending message", ex);
+
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
index 6d73f98ad..ffd98bf78 100644
--- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
+++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
@@ -1,7 +1,7 @@
using Emby.Server.Implementations.Browser;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Controller.Configuration;
namespace Emby.Server.Implementations.EntryPoints
@@ -61,4 +61,4 @@ namespace Emby.Server.Implementations.EntryPoints
{
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
index 5edc5fade..730ced055 100644
--- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
+++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
@@ -1,7 +1,7 @@
using System;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using Emby.Server.Implementations.Udp;
using MediaBrowser.Model.Net;
@@ -45,9 +45,6 @@ namespace Emby.Server.Implementations.EntryPoints
/// </summary>
public void Run()
{
- // ToDo: Fix This
- return;
-
var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory);
try
@@ -58,7 +55,7 @@ namespace Emby.Server.Implementations.EntryPoints
}
catch (Exception ex)
{
- _logger.ErrorException("Failed to start UDP Server", ex);
+ _logger.LogError(ex, "Failed to start UDP Server");
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs
deleted file mode 100644
index 450764040..000000000
--- a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Extensions;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- /// <summary>
- /// Class UsageEntryPoint
- /// </summary>
- public class UsageEntryPoint : IServerEntryPoint
- {
- private readonly IServerApplicationHost _applicationHost;
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private readonly ISessionManager _sessionManager;
- private readonly IUserManager _userManager;
- private readonly IServerConfigurationManager _config;
-
- private readonly ConcurrentDictionary<Guid, ClientInfo> _apps = new ConcurrentDictionary<Guid, ClientInfo>();
-
- public UsageEntryPoint(ILogger logger, IServerApplicationHost applicationHost, IHttpClient httpClient, ISessionManager sessionManager, IUserManager userManager, IServerConfigurationManager config)
- {
- _logger = logger;
- _applicationHost = applicationHost;
- _httpClient = httpClient;
- _sessionManager = sessionManager;
- _userManager = userManager;
- _config = config;
-
- _sessionManager.SessionStarted += _sessionManager_SessionStarted;
- }
-
- void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
- {
- var session = e.SessionInfo;
-
- if (!string.IsNullOrEmpty(session.Client) &&
- !string.IsNullOrEmpty(session.DeviceName) &&
- !string.IsNullOrEmpty(session.DeviceId) &&
- !string.IsNullOrEmpty(session.ApplicationVersion))
- {
- var keys = new List<string>
- {
- session.Client,
- session.DeviceName,
- session.DeviceId,
- session.ApplicationVersion
- };
-
- var key = string.Join("_", keys.ToArray()).GetMD5();
-
- ClientInfo info;
- if (!_apps.TryGetValue(key, out info))
- {
- info = new ClientInfo
- {
- AppName = session.Client,
- AppVersion = session.ApplicationVersion,
- DeviceName = session.DeviceName,
- DeviceId = session.DeviceId
- };
-
- _apps[key] = info;
-
- if (_config.Configuration.EnableAnonymousUsageReporting)
- {
- Task.Run(() => ReportNewSession(info));
- }
- }
- }
- }
-
- private async Task ReportNewSession(ClientInfo client)
- {
- try
- {
- await new UsageReporter(_applicationHost, _httpClient, _logger)
- .ReportAppUsage(client, CancellationToken.None)
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- //_logger.ErrorException("Error sending anonymous usage statistics.", ex);
- }
- }
-
- public async void Run()
- {
- await Task.Delay(5000).ConfigureAwait(false);
- OnTimerFired();
- }
-
- /// <summary>
- /// Called when [timer fired].
- /// </summary>
- private async void OnTimerFired()
- {
- if (!_config.Configuration.EnableAnonymousUsageReporting)
- {
- return;
- }
-
- try
- {
- await new UsageReporter(_applicationHost, _httpClient, _logger)
- .ReportServerUsage(CancellationToken.None)
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- //_logger.ErrorException("Error sending anonymous usage statistics.", ex);
- }
- }
-
- public void Dispose()
- {
- _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs
deleted file mode 100644
index d9c9e1a40..000000000
--- a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using MediaBrowser.Common;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Connect;
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller;
-using MediaBrowser.Model.Logging;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- public class UsageReporter
- {
- private readonly IServerApplicationHost _applicationHost;
- private readonly IHttpClient _httpClient;
- private readonly ILogger _logger;
- private const string MbAdminUrl = "https://www.mb3admin.local/admin/";
-
- public UsageReporter(IServerApplicationHost applicationHost, IHttpClient httpClient, ILogger logger)
- {
- _applicationHost = applicationHost;
- _httpClient = httpClient;
- _logger = logger;
- }
-
- public async Task ReportServerUsage(CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- var data = new Dictionary<string, string>
- {
- { "feature", _applicationHost.Name },
- { "mac", _applicationHost.SystemId },
- { "serverid", _applicationHost.SystemId },
- { "deviceid", _applicationHost.SystemId },
- { "ver", _applicationHost.ApplicationVersion.ToString() },
- { "platform", _applicationHost.OperatingSystemDisplayName }
- };
-
- data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray());
-
- var logErrors = false;
-#if DEBUG
- logErrors = true;
-#endif
- var options = new HttpRequestOptions
- {
- Url = MbAdminUrl + "service/registration/ping",
- CancellationToken = cancellationToken,
-
- // Seeing block length errors
- EnableHttpCompression = false,
-
- LogRequest = false,
- LogErrors = logErrors,
- BufferContent = false
- };
-
- options.SetPostData(data);
-
- using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
- {
-
- }
- }
-
- public async Task ReportAppUsage(ClientInfo app, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(app.DeviceId))
- {
- throw new ArgumentException("Client info must have a device Id");
- }
-
- _logger.Info("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}",
- app.AppName ?? "Unknown App",
- app.AppVersion ?? "Unknown",
- app.DeviceId,
- app.DeviceName ?? "Unknown");
-
- cancellationToken.ThrowIfCancellationRequested();
-
- var data = new Dictionary<string, string>
- {
- { "feature", app.AppName ?? "Unknown App" },
- { "serverid", _applicationHost.SystemId },
- { "deviceid", app.DeviceId },
- { "mac", app.DeviceId },
- { "ver", app.AppVersion ?? "Unknown" },
- { "platform", app.DeviceName },
- };
-
- var logErrors = false;
-
-#if DEBUG
- logErrors = true;
-#endif
- var options = new HttpRequestOptions
- {
- Url = MbAdminUrl + "service/registration/ping",
- CancellationToken = cancellationToken,
-
- // Seeing block length errors
- EnableHttpCompression = false,
-
- LogRequest = false,
- LogErrors = logErrors,
- BufferContent = false
- };
-
- options.SetPostData(data);
-
- using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
- {
-
- }
- }
- }
-
- public class ClientInfo
- {
- public string AppName { get; set; }
- public string AppVersion { get; set; }
- public string DeviceName { get; set; }
- public string DeviceId { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index 36e29e46a..58309ea1c 100644
--- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Session;
using System;
using System.Collections.Generic;
diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
index 583e93706..03e10e7ea 100644
--- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
+++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
@@ -1,46 +1,33 @@
using System;
using System.IO;
using MediaBrowser.Model.System;
+using System.Runtime.InteropServices;
namespace Emby.Server.Implementations.EnvironmentInfo
{
+ // TODO: Rework @bond
public class EnvironmentInfo : IEnvironmentInfo
{
- private Architecture? _customArchitecture;
- private MediaBrowser.Model.System.OperatingSystem? _customOperatingSystem;
-
- public virtual MediaBrowser.Model.System.OperatingSystem OperatingSystem
+ public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem)
{
- get
- {
- if (_customOperatingSystem.HasValue)
- {
- return _customOperatingSystem.Value;
- }
-
- switch (Environment.OSVersion.Platform)
- {
- case PlatformID.MacOSX:
- return MediaBrowser.Model.System.OperatingSystem.OSX;
- case PlatformID.Win32NT:
- return MediaBrowser.Model.System.OperatingSystem.Windows;
- case PlatformID.Unix:
- return MediaBrowser.Model.System.OperatingSystem.Linux;
- }
-
- return MediaBrowser.Model.System.OperatingSystem.Windows;
- }
- set
- {
- _customOperatingSystem = value;
- }
+ OperatingSystem = operatingSystem;
}
+ public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; }
+
public string OperatingSystemName
{
get
{
- return Environment.OSVersion.Platform.ToString();
+ switch (OperatingSystem)
+ {
+ case MediaBrowser.Model.System.OperatingSystem.Android: return "Android";
+ case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD";
+ case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux";
+ case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS";
+ case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows";
+ default: throw new Exception($"Unknown OS {OperatingSystem}");
+ }
}
}
@@ -60,22 +47,7 @@ namespace Emby.Server.Implementations.EnvironmentInfo
}
}
- public Architecture SystemArchitecture
- {
- get
- {
- if (_customArchitecture.HasValue)
- {
- return _customArchitecture.Value;
- }
-
- return Environment.Is64BitOperatingSystem ? MediaBrowser.Model.System.Architecture.X64 : MediaBrowser.Model.System.Architecture.X86;
- }
- set
- {
- _customArchitecture = value;
- }
- }
+ public Architecture SystemArchitecture { get { return RuntimeInformation.OSArchitecture; } }
public string GetEnvironmentVariable(string name)
{
@@ -92,4 +64,4 @@ namespace Emby.Server.Implementations.EnvironmentInfo
Environment.SetEnvironmentVariable(name, value);
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
index fe1df0953..5f043e127 100644
--- a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
+++ b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
index d53606e87..d3ba1b683 100644
--- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
+++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
@@ -5,18 +5,16 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
-using System.Net.Sockets;
+using System.Net.Cache;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
-using Emby.Server.Implementations.IO;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
-using MediaBrowser.Controller.IO;
namespace Emby.Server.Implementations.HttpClientManager
{
@@ -125,59 +123,38 @@ namespace Emby.Server.Implementations.HttpClientManager
private WebRequest GetRequest(HttpRequestOptions options, string method)
{
- var url = options.Url;
+ string url = options.Url;
- var uriAddress = new Uri(url);
- var userInfo = uriAddress.UserInfo;
+ Uri uriAddress = new Uri(url);
+ string userInfo = uriAddress.UserInfo;
if (!string.IsNullOrWhiteSpace(userInfo))
{
- _logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url);
+ _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url);
url = url.Replace(userInfo + "@", string.Empty);
}
- var request = CreateWebRequest(url);
- var httpWebRequest = request as HttpWebRequest;
+ WebRequest request = CreateWebRequest(url);
- if (httpWebRequest != null)
+ if (request is HttpWebRequest httpWebRequest)
{
AddRequestHeaders(httpWebRequest, options);
if (options.EnableHttpCompression)
{
- if (options.DecompressionMethod.HasValue)
- {
- httpWebRequest.AutomaticDecompression = options.DecompressionMethod.Value == CompressionMethod.Gzip
- ? DecompressionMethods.GZip
- : DecompressionMethods.Deflate;
- }
- else
+ httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
+ if (options.DecompressionMethod.HasValue
+ && options.DecompressionMethod.Value == CompressionMethod.Gzip)
{
- httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
+ httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
}
}
else
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
}
- }
-
-
-
- request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
-
- if (httpWebRequest != null)
- {
- if (options.EnableKeepAlive)
- {
- httpWebRequest.KeepAlive = true;
- }
- }
- request.Method = method;
- request.Timeout = options.TimeoutMs;
+ httpWebRequest.KeepAlive = options.EnableKeepAlive;
- if (httpWebRequest != null)
- {
if (!string.IsNullOrEmpty(options.Host))
{
httpWebRequest.Host = options.Host;
@@ -189,6 +166,11 @@ namespace Emby.Server.Implementations.HttpClientManager
}
}
+ request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
+
+ request.Method = method;
+ request.Timeout = options.TimeoutMs;
+
if (!string.IsNullOrWhiteSpace(userInfo))
{
var parts = userInfo.Split(':');
@@ -215,7 +197,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{
var hasUserAgent = false;
- foreach (var header in options.RequestHeaders.ToList())
+ foreach (var header in options.RequestHeaders)
{
if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
{
@@ -379,10 +361,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{
try
{
- // TODO: We can always put this in the options object if needed
- var requestEncoding = Encoding.UTF8;
-
- var bytes = options.RequestContentBytes ?? requestEncoding.GetBytes(options.RequestContent ?? string.Empty);
+ var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
@@ -392,7 +371,6 @@ namespace Emby.Server.Implementations.HttpClientManager
}
httpWebRequest.ContentType = contentType;
-
httpWebRequest.ContentLength = bytes.Length;
(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
}
@@ -409,10 +387,7 @@ namespace Emby.Server.Implementations.HttpClientManager
if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
{
- if (options.ResourcePool != null)
- {
- options.ResourcePool.Release();
- }
+ options.ResourcePool?.Release();
throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
}
@@ -421,11 +396,11 @@ namespace Emby.Server.Implementations.HttpClientManager
{
if (options.LogRequestAsDebug)
{
- _logger.Debug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
+ _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
}
else
{
- _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
+ _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
}
}
@@ -457,7 +432,6 @@ namespace Emby.Server.Implementations.HttpClientManager
using (var stream = httpResponse.GetResponseStream())
{
var memoryStream = new MemoryStream();
-
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Position = 0;
@@ -476,10 +450,7 @@ namespace Emby.Server.Implementations.HttpClientManager
}
finally
{
- if (options.ResourcePool != null)
- {
- options.ResourcePool.Release();
- }
+ options.ResourcePool?.Release();
}
}
@@ -488,13 +459,9 @@ namespace Emby.Server.Implementations.HttpClientManager
var responseInfo = new HttpResponseInfo(disposable)
{
Content = content,
-
StatusCode = httpResponse.StatusCode,
-
ContentType = httpResponse.ContentType,
-
ContentLength = contentLength,
-
ResponseUrl = httpResponse.ResponseUri.ToString()
};
@@ -511,11 +478,8 @@ namespace Emby.Server.Implementations.HttpClientManager
var responseInfo = new HttpResponseInfo
{
TempFilePath = tempFile,
-
StatusCode = httpResponse.StatusCode,
-
ContentType = httpResponse.ContentType,
-
ContentLength = contentLength
};
@@ -595,11 +559,11 @@ namespace Emby.Server.Implementations.HttpClientManager
{
if (options.LogRequestAsDebug)
{
- _logger.Debug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
+ _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
}
else
{
- _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
+ _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
}
}
@@ -619,22 +583,20 @@ namespace Emby.Server.Implementations.HttpClientManager
var contentLength = GetContentLength(httpResponse);
- if (!contentLength.HasValue)
+ if (contentLength.HasValue)
{
- // We're not able to track progress
- using (var stream = httpResponse.GetResponseStream())
+ using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
- using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
- }
+ await httpResponse.GetResponseStream().CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
}
}
else
{
+ // We're not able to track progress
+ using (var stream = httpResponse.GetResponseStream())
using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
- await httpResponse.GetResponseStream().CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
+ await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
}
}
@@ -650,10 +612,7 @@ namespace Emby.Server.Implementations.HttpClientManager
}
finally
{
- if (options.ResourcePool != null)
- {
- options.ResourcePool.Release();
- }
+ options.ResourcePool?.Release();
}
}
@@ -685,7 +644,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{
if (options.LogErrors)
{
- _logger.ErrorException("Error " + webException.Status + " getting response from " + options.Url, webException);
+ _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
}
var exception = new HttpException(webException.Message, webException);
@@ -723,7 +682,7 @@ namespace Emby.Server.Implementations.HttpClientManager
if (options.LogErrors)
{
- _logger.ErrorException("Error getting response from " + options.Url, ex);
+ _logger.LogError(ex, "Error getting response from {url}", options.Url);
}
return ex;
@@ -789,7 +748,7 @@ namespace Emby.Server.Implementations.HttpClientManager
if (options.LogErrors)
{
- _logger.Error(msg);
+ _logger.LogError(msg);
}
client.LastTimeout = DateTime.UtcNow;
@@ -810,35 +769,38 @@ namespace Emby.Server.Implementations.HttpClientManager
var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
- if (!isSuccessful)
+ if (isSuccessful)
{
- if (options.LogErrorResponseBody)
+ return;
+ }
+
+ if (options.LogErrorResponseBody)
+ {
+ try
{
- try
+ using (var stream = response.GetResponseStream())
{
- using (var stream = response.GetResponseStream())
+ if (stream != null)
{
- if (stream != null)
+ using (var reader = new StreamReader(stream))
{
- using (var reader = new StreamReader(stream))
- {
- var msg = reader.ReadToEnd();
+ var msg = reader.ReadToEnd();
- _logger.Error(msg);
- }
+ _logger.LogError(msg);
}
}
}
- catch
- {
-
- }
}
- throw new HttpException(response.StatusDescription)
+ catch
{
- StatusCode = response.StatusCode
- };
+
+ }
}
+
+ throw new HttpException(response.StatusDescription)
+ {
+ StatusCode = response.StatusCode
+ };
}
private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
@@ -859,13 +821,10 @@ namespace Emby.Server.Implementations.HttpClientManager
private static void TimeoutCallback(object state, bool timedOut)
{
- if (timedOut)
+ if (timedOut && state != null)
{
WebRequest request = (WebRequest)state;
- if (state != null)
- {
- request.Abort();
- }
+ request.Abort();
}
}
@@ -880,13 +839,13 @@ namespace Emby.Server.Implementations.HttpClientManager
public void OnError(Task<WebResponse> task)
{
- if (task.Exception != null)
+ if (task.Exception == null)
{
- taskCompletion.TrySetException(task.Exception);
+ taskCompletion.TrySetException(Enumerable.Empty<Exception>());
}
else
{
- taskCompletion.TrySetException(new List<Exception>());
+ taskCompletion.TrySetException(task.Exception);
}
}
}
diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs
index 353ba5282..1a875e533 100644
--- a/Emby.Server.Implementations/HttpServer/FileWriter.cs
+++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs
@@ -5,7 +5,7 @@ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Services;
using System.Linq;
@@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.HttpServer
var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
Headers["Content-Range"] = rangeString;
- Logger.Info("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
+ Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
}
/// <summary>
@@ -173,7 +173,7 @@ namespace Emby.Server.Implementations.HttpServer
if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
- Logger.Debug("Transmit file {0}", path);
+ Logger.LogDebug("Transmit file {0}", path);
}
//var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
index 70a233c6f..69ca0f85b 100644
--- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
+++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
@@ -1,14 +1,13 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
-using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -16,17 +15,12 @@ using Emby.Server.Implementations.Services;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Security;
using MediaBrowser.Controller;
-using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
using System.Net.Sockets;
using Emby.Server.Implementations.Net;
-using MediaBrowser.Common.Events;
using MediaBrowser.Model.Events;
namespace Emby.Server.Implementations.HttpServer
@@ -184,7 +178,7 @@ namespace Emby.Server.Implementations.HttpServer
if (WebSocketConnected != null)
{
- EventHelper.FireEventIfNotNull(WebSocketConnected, this, new GenericEventArgs<IWebSocketConnection>(connection), _logger);
+ WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
}
}
@@ -252,11 +246,11 @@ namespace Emby.Server.Implementations.HttpServer
if (logExceptionStackTrace)
{
- _logger.ErrorException("Error processing request", ex);
+ _logger.LogError(ex, "Error processing request");
}
else if (logExceptionMessage)
{
- _logger.Error(ex.Message);
+ _logger.LogError(ex.Message);
}
var httpRes = httpReq.Response;
@@ -272,9 +266,9 @@ namespace Emby.Server.Implementations.HttpServer
httpRes.ContentType = "text/html";
await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false);
}
- catch
+ catch (Exception errorEx)
{
- //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
+ _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
}
}
@@ -320,10 +314,10 @@ namespace Emby.Server.Implementations.HttpServer
if (_listener != null)
{
- _logger.Info("Stopping HttpListener...");
+ _logger.LogInformation("Stopping HttpListener...");
var task = _listener.Stop();
Task.WaitAll(task);
- _logger.Info("HttpListener stopped");
+ _logger.LogInformation("HttpListener stopped");
}
}
@@ -713,12 +707,12 @@ namespace Emby.Server.Implementations.HttpServer
var pathParts = pathInfo.TrimStart('/').Split('/');
if (pathParts.Length == 0)
{
- _logger.Error("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl);
+ _logger.LogError("Path parts empty for PathInfo: {pathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
return null;
}
string contentType;
- var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, _logger, out contentType);
+ var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType);
if (restPath != null)
{
@@ -729,7 +723,7 @@ namespace Emby.Server.Implementations.HttpServer
};
}
- _logger.Error("Could not find handler for {0}", pathInfo);
+ _logger.LogError("Could not find handler for {pathInfo}", pathInfo);
return null;
}
@@ -783,7 +777,7 @@ namespace Emby.Server.Implementations.HttpServer
ServiceController = new ServiceController();
- _logger.Info("Calling ServiceStack AppHost.Init");
+ _logger.LogInformation("Calling ServiceStack AppHost.Init");
var types = services.Select(r => r.GetType()).ToArray();
@@ -853,7 +847,7 @@ namespace Emby.Server.Implementations.HttpServer
//using (var reader = new StreamReader(stream))
//{
// var json = reader.ReadToEnd();
- // Logger.Info(json);
+ // logger.LogInformation(json);
// return _jsonSerializer.DeserializeFromString(json, type);
//}
return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
@@ -919,7 +913,7 @@ namespace Emby.Server.Implementations.HttpServer
return Task.CompletedTask;
}
- //_logger.Debug("Websocket message received: {0}", result.MessageType);
+ _logger.LogDebug("Websocket message received: {0}", result.MessageType);
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
{
@@ -929,7 +923,7 @@ namespace Emby.Server.Implementations.HttpServer
}
catch (Exception ex)
{
- _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty);
+ _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
}
}));
diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
index a0a471cb2..73b2afe64 100644
--- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
+++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
@@ -37,12 +37,12 @@ namespace Emby.Server.Implementations.HttpServer
/// <summary>
/// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
/// </summary>
- public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
+ public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
{
_fileSystem = fileSystem;
_jsonSerializer = jsonSerializer;
_brotliCompressor = brotliCompressor;
- _logger = logManager.GetLogger("HttpResultFactory");
+ _logger = loggerfactory.CreateLogger("HttpResultFactory");
}
/// <summary>
diff --git a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs
index 3aa48efd4..5b7bbe79c 100644
--- a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs
+++ b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
using MediaBrowser.Model.Services;
@@ -11,7 +11,7 @@ namespace Emby.Server.Implementations.HttpServer
{
if (headers == null)
{
- logger.Info("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty);
+ logger.LogInformation("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty);
}
else
{
@@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.HttpServer
index++;
}
- logger.Info("HTTP {0} {1}. {2}", method, url, headerText);
+ logger.LogInformation("HTTP {0} {1}. {2}", method, url, headerText);
}
}
@@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.HttpServer
//var headerText = headers == null ? string.Empty : "Headers: " + string.Join(", ", headers.Where(i => i.Name.IndexOf("Access-", StringComparison.OrdinalIgnoreCase) == -1).Select(i => i.Name + "=" + i.Value).ToArray());
var headerText = string.Empty;
- logger.Info("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText);
+ logger.LogInformation("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText);
}
}
}
diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
index 4177c7e78..dc20ee1a2 100644
--- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
+++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -226,4 +226,4 @@ namespace Emby.Server.Implementations.HttpServer
public string StatusDescription { get; set; }
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
index 385d19b6b..f38aa5ea0 100644
--- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
+++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
using System.Text;
@@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.HttpServer
if (exception != null)
{
- _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl);
+ _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl);
if (!string.IsNullOrEmpty(exception.Message))
{
diff --git a/Emby.Server.Implementations/HttpServer/StreamWriter.cs b/Emby.Server.Implementations/HttpServer/StreamWriter.cs
index 3f394d3ac..0a44a5fe5 100644
--- a/Emby.Server.Implementations/HttpServer/StreamWriter.cs
+++ b/Emby.Server.Implementations/HttpServer/StreamWriter.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
index d449e4424..914fa9dbc 100644
--- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
+++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
@@ -1,7 +1,6 @@
using System.Text;
-using MediaBrowser.Common.Events;
using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using System;
@@ -118,7 +117,7 @@ namespace Emby.Server.Implementations.HttpServer
void socket_Closed(object sender, EventArgs e)
{
- EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
+ Closed?.Invoke(this, EventArgs.Empty);
}
/// <summary>
@@ -180,7 +179,7 @@ namespace Emby.Server.Implementations.HttpServer
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
{
// This info is useful sometimes but also clogs up the log
- //_logger.Error("Received web socket message that is not a json structure: " + message);
+ _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
return;
}
@@ -204,7 +203,7 @@ namespace Emby.Server.Implementations.HttpServer
}
catch (Exception ex)
{
- _logger.ErrorException("Error processing web socket message", ex);
+ _logger.LogError(ex, "Error processing web socket message");
}
}
diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs
index 4be30f8b7..34c711324 100644
--- a/Emby.Server.Implementations/IO/FileRefresher.cs
+++ b/Emby.Server.Implementations/IO/FileRefresher.cs
@@ -2,17 +2,12 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Threading;
@@ -38,7 +33,7 @@ namespace Emby.Server.Implementations.IO
public FileRefresher(string path, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ITaskManager taskManager, ILogger logger, ITimerFactory timerFactory, IEnvironmentInfo environmentInfo, ILibraryManager libraryManager1)
{
- logger.Debug("New file refresher created for {0}", path);
+ logger.LogDebug("New file refresher created for {0}", path);
Path = path;
_fileSystem = fileSystem;
@@ -108,7 +103,7 @@ namespace Emby.Server.Implementations.IO
{
lock (_timerLock)
{
- Logger.Debug("Resetting file refresher from {0} to {1}", Path, path);
+ Logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
Path = path;
AddAffectedPath(path);
@@ -130,10 +125,10 @@ namespace Emby.Server.Implementations.IO
paths = _affectedPaths.ToList();
}
- Logger.Debug("Timer stopped.");
+ Logger.LogDebug("Timer stopped.");
DisposeTimer();
- EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger);
+ Completed?.Invoke(this, EventArgs.Empty);
try
{
@@ -141,7 +136,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Error processing directory changes", ex);
+ Logger.LogError(ex, "Error processing directory changes");
}
}
@@ -161,7 +156,7 @@ namespace Emby.Server.Implementations.IO
continue;
}
- Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
+ Logger.LogInformation("{name} ({path}}) will be refreshed.", item.Name, item.Path);
try
{
@@ -172,11 +167,11 @@ namespace Emby.Server.Implementations.IO
// For now swallow and log.
// Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
// Should we remove it from it's parent?
- Logger.ErrorException("Error refreshing {0}", ex, item.Name);
+ Logger.LogError(ex, "Error refreshing {name}", item.Name);
}
catch (Exception ex)
{
- Logger.ErrorException("Error refreshing {0}", ex, item.Name);
+ Logger.LogError(ex, "Error refreshing {name}", item.Name);
}
}
}
diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs
index 00fe447f0..ca5810fd6 100644
--- a/Emby.Server.Implementations/IO/LibraryMonitor.cs
+++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Threading;
@@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, path);
+ Logger.LogError(ex, "Error in ReportFileSystemChanged for {path}", path);
}
}
}
@@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
/// </summary>
- public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo)
+ public LibraryMonitor(ILoggerFactory loggerFactory, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo)
{
if (taskManager == null)
{
@@ -150,7 +150,7 @@ namespace Emby.Server.Implementations.IO
LibraryManager = libraryManager;
TaskManager = taskManager;
- Logger = logManager.GetLogger(GetType().Name);
+ Logger = loggerFactory.CreateLogger(GetType().Name);
ConfigurationManager = configurationManager;
_fileSystem = fileSystem;
_timerFactory = timerFactory;
@@ -291,7 +291,7 @@ namespace Emby.Server.Implementations.IO
if (!_fileSystem.DirectoryExists(path))
{
// Seeing a crash in the mono runtime due to an exception being thrown on a different thread
- Logger.Info("Skipping realtime monitor for {0} because the path does not exist", path);
+ Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path);
return;
}
@@ -344,7 +344,7 @@ namespace Emby.Server.Implementations.IO
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
- Logger.Info("Watching directory " + path);
+ Logger.LogInformation("Watching directory " + path);
}
else
{
@@ -354,7 +354,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Error watching path: {0}", ex, path);
+ Logger.LogError(ex, "Error watching path: {path}", path);
}
});
}
@@ -382,7 +382,7 @@ namespace Emby.Server.Implementations.IO
{
using (watcher)
{
- Logger.Info("Stopping directory watching for path {0}", watcher.Path);
+ Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path);
watcher.Created -= watcher_Changed;
watcher.Deleted -= watcher_Changed;
@@ -439,7 +439,7 @@ namespace Emby.Server.Implementations.IO
var ex = e.GetException();
var dw = (FileSystemWatcher)sender;
- Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
+ Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path);
DisposeWatcher(dw, true);
}
@@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.IO
{
try
{
- //Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
+ //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
var path = e.FullPath;
@@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
+ Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
}
}
@@ -487,13 +487,13 @@ namespace Emby.Server.Implementations.IO
{
if (_fileSystem.AreEqual(i, path))
{
- //Logger.Debug("Ignoring change to {0}", path);
+ Logger.LogDebug("Ignoring change to {path}", path);
return true;
}
if (_fileSystem.ContainsSubPath(i, path))
{
- //Logger.Debug("Ignoring change to {0}", path);
+ Logger.LogDebug("Ignoring change to {path}", path);
return true;
}
@@ -503,7 +503,7 @@ namespace Emby.Server.Implementations.IO
{
if (_fileSystem.AreEqual(parent, path))
{
- //Logger.Debug("Ignoring change to {0}", path);
+ Logger.LogDebug("Ignoring change to {path}", path);
return true;
}
}
diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
index 66d7802c6..0f85e0642 100644
--- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs
+++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
@@ -5,7 +5,7 @@ using System.IO;
using System.Linq;
using System.Text;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
namespace Emby.Server.Implementations.IO
@@ -24,7 +24,6 @@ namespace Emby.Server.Implementations.IO
private string _tempPath;
- private SharpCifsFileSystem _sharpCifsFileSystem;
private IEnvironmentInfo _environmentInfo;
private bool _isEnvironmentCaseInsensitive;
@@ -43,8 +42,6 @@ namespace Emby.Server.Implementations.IO
SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
- _sharpCifsFileSystem = new SharpCifsFileSystem(environmentInfo.OperatingSystem);
-
_isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
}
@@ -175,7 +172,7 @@ namespace Emby.Server.Implementations.IO
path = System.IO.Path.GetFullPath(path);
return path;
}
- catch (ArgumentException ex)
+ catch (ArgumentException)
{
return filePath;
}
@@ -233,11 +230,6 @@ namespace Emby.Server.Implementations.IO
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
public FileSystemMetadata GetFileSystemInfo(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileSystemInfo(path);
- }
-
// Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
if (Path.HasExtension(path))
{
@@ -273,11 +265,6 @@ namespace Emby.Server.Implementations.IO
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetFileInfo(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileInfo(path);
- }
-
var fileInfo = new FileInfo(path);
return GetFileSystemMetadata(fileInfo);
@@ -293,11 +280,6 @@ namespace Emby.Server.Implementations.IO
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetDirectoryInfo(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetDirectoryInfo(path);
- }
-
var fileInfo = new DirectoryInfo(path);
return GetFileSystemMetadata(fileInfo);
@@ -395,7 +377,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
+ Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -434,7 +416,7 @@ namespace Emby.Server.Implementations.IO
}
catch (Exception ex)
{
- Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName);
+ Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
return DateTime.MinValue;
}
}
@@ -460,11 +442,6 @@ namespace Emby.Server.Implementations.IO
/// <returns>FileStream.</returns>
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
- }
-
if (_supportsAsyncFileStreams && isAsync)
{
return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
@@ -475,11 +452,6 @@ namespace Emby.Server.Implementations.IO
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
- }
-
var defaultBufferSize = 4096;
return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions));
}
@@ -550,12 +522,6 @@ namespace Emby.Server.Implementations.IO
return;
}
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.SetHidden(path, isHidden);
- return;
- }
-
var info = GetExtendedFileSystemInfo(path);
if (info.Exists && info.IsHidden != isHidden)
@@ -580,12 +546,6 @@ namespace Emby.Server.Implementations.IO
return;
}
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.SetReadOnly(path, isReadOnly);
- return;
- }
-
var info = GetExtendedFileSystemInfo(path);
if (info.Exists && info.IsReadOnly != isReadOnly)
@@ -610,12 +570,6 @@ namespace Emby.Server.Implementations.IO
return;
}
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.SetAttributes(path, isHidden, isReadOnly);
- return;
- }
-
var info = GetExtendedFileSystemInfo(path);
if (!info.Exists)
@@ -688,11 +642,6 @@ namespace Emby.Server.Implementations.IO
private char GetDirectorySeparatorChar(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
- }
-
return Path.DirectorySeparatorChar;
}
@@ -732,11 +681,6 @@ namespace Emby.Server.Implementations.IO
public string GetDirectoryName(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetDirectoryName(path);
- }
-
return Path.GetDirectoryName(path);
}
@@ -747,11 +691,6 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException("path");
}
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.NormalizePath(path);
- }
-
if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
{
return path;
@@ -794,11 +733,6 @@ namespace Emby.Server.Implementations.IO
{
// Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return true;
- }
-
if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
!path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
@@ -812,35 +746,17 @@ namespace Emby.Server.Implementations.IO
public void DeleteFile(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.DeleteFile(path);
- return;
- }
-
SetAttributes(path, false, false);
File.Delete(path);
}
public void DeleteDirectory(string path, bool recursive)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.DeleteDirectory(path, recursive);
- return;
- }
-
Directory.Delete(path, recursive);
}
public void CreateDirectory(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.CreateDirectory(path);
- return;
- }
-
Directory.CreateDirectory(path);
}
@@ -863,11 +779,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetDirectories(path, recursive);
- }
-
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
@@ -880,11 +791,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
- }
-
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// On linux and osx the search pattern is case sensitive
@@ -914,11 +820,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
- }
-
var directoryInfo = new DirectoryInfo(path);
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
@@ -938,29 +839,16 @@ namespace Emby.Server.Implementations.IO
public string[] ReadAllLines(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.ReadAllLines(path);
- }
return File.ReadAllLines(path);
}
public void WriteAllLines(string path, IEnumerable<string> lines)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.WriteAllLines(path, lines);
- return;
- }
File.WriteAllLines(path, lines);
}
public Stream OpenRead(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.OpenRead(path);
- }
return File.OpenRead(path);
}
@@ -977,128 +865,61 @@ namespace Emby.Server.Implementations.IO
public void CopyFile(string source, string target, bool overwrite)
{
- var enableSharpCifsForSource = _sharpCifsFileSystem.IsEnabledForPath(source);
-
- if (enableSharpCifsForSource != _sharpCifsFileSystem.IsEnabledForPath(target))
- {
- CopyFileUsingStreams(source, target, overwrite);
- return;
- }
-
- if (enableSharpCifsForSource)
- {
- _sharpCifsFileSystem.CopyFile(source, target, overwrite);
- return;
- }
File.Copy(source, target, overwrite);
}
public void MoveFile(string source, string target)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(source))
- {
- _sharpCifsFileSystem.MoveFile(source, target);
- return;
- }
File.Move(source, target);
}
public void MoveDirectory(string source, string target)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(source))
- {
- _sharpCifsFileSystem.MoveDirectory(source, target);
- return;
- }
Directory.Move(source, target);
}
public bool DirectoryExists(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.DirectoryExists(path);
- }
return Directory.Exists(path);
}
public bool FileExists(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.FileExists(path);
- }
return File.Exists(path);
}
public string ReadAllText(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.ReadAllText(path);
- }
return File.ReadAllText(path);
}
public byte[] ReadAllBytes(string path)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.ReadAllBytes(path);
- }
return File.ReadAllBytes(path);
}
public void WriteAllText(string path, string text, Encoding encoding)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.WriteAllText(path, text, encoding);
- return;
- }
-
File.WriteAllText(path, text, encoding);
}
public void WriteAllText(string path, string text)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.WriteAllText(path, text);
- return;
- }
-
File.WriteAllText(path, text);
}
public void WriteAllBytes(string path, byte[] bytes)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- _sharpCifsFileSystem.WriteAllBytes(path, bytes);
- return;
- }
-
File.WriteAllBytes(path, bytes);
}
public string ReadAllText(string path, Encoding encoding)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.ReadAllText(path, encoding);
- }
-
return File.ReadAllText(path, encoding);
}
public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
- }
-
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateDirectories(path, "*", searchOption);
}
@@ -1110,11 +931,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
- }
-
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// On linux and osx the search pattern is case sensitive
@@ -1144,11 +960,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{
- if (_sharpCifsFileSystem.IsEnabledForPath(path))
- {
- return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
- }
-
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Config.cs b/Emby.Server.Implementations/IO/SharpCifs/Config.cs
deleted file mode 100644
index 3fd0e5bd6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Config.cs
+++ /dev/null
@@ -1,409 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using System.Net;
-using System.Security;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs
-{
- /// <summary>
- /// This class uses a static
- /// <see cref="Properties">Sharpen.Properties</see>
- /// to act
- /// as a cental repository for all jCIFS configuration properties. It cannot be
- /// instantiated. Similar to <code>System</code> properties the namespace
- /// is global therefore property names should be unique. Before use,
- /// the <code>load</code> method should be called with the name of a
- /// <code>Properties</code> file (or <code>null</code> indicating no
- /// file) to initialize the <code>Config</code>. The <code>System</code>
- /// properties will then populate the <code>Config</code> as well potentially
- /// overwriting properties from the file. Thus properties provided on the
- /// commandline with the <code>-Dproperty.name=value</code> VM parameter
- /// will override properties from the configuration file.
- ///
- /// There are several ways to set jCIFS properties. See
- /// the <a href="../overview-summary.html#scp">overview page of the API
- /// documentation</a> for details.
- /// </summary>
- public class Config
- {
-
- /// <summary>The static <code>Properties</code>.</summary>
- /// <remarks>The static <code>Properties</code>.</remarks>
- private static Properties _prp = new Properties();
-
- private static LogStream _log;
-
- public static string DefaultOemEncoding = "UTF-8"; //"Cp850";
-
- static Config()
- {
- int level;
- FileInputStream fis = null;
- _log = LogStream.GetInstance();
-
- try
- {
- string filename = Runtime.GetProperty("jcifs.properties");
- if (filename != null && filename.Length > 1)
- {
- fis = new FileInputStream(filename);
- }
- Load(fis);
- if (fis != null)
- {
- fis.Close();
- }
- }
- catch (IOException ioe)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- }
-
- if ((level = GetInt("jcifs.util.loglevel", -1)) != -1)
- {
- _log.SetLevel(level);
- }
-
- try
- {
- Runtime.GetBytesForString(string.Empty, DefaultOemEncoding);
- }
- catch (Exception ex)
- {
- if (_log.Level >= 2)
- {
- _log.WriteLine("WARNING: The default OEM encoding " + DefaultOemEncoding + " does not appear to be supported by this JRE. The default encoding will be US-ASCII."
- );
- }
-
- //DEFAULT_OEM_ENCODING = "US-ASCII";
- }
-
- if (_log.Level >= 4)
- {
- try
- {
- _prp.Store(_log);
- }
- catch (IOException)
- {
- }
- }
- }
-
- /// <summary>
- /// This static method registers the SMB URL protocol handler which is
- /// required to use SMB URLs with the <tt>java.net.URL</tt> class.
- /// </summary>
- /// <remarks>
- /// This static method registers the SMB URL protocol handler which is
- /// required to use SMB URLs with the <tt>java.net.URL</tt> class. If this
- /// method is not called before attempting to create an SMB URL with the
- /// URL class the following exception will occur:
- /// <blockquote><pre>
- /// Exception MalformedURLException: unknown protocol: smb
- /// at java.net.URL.<init>(URL.java:480)
- /// at java.net.URL.<init>(URL.java:376)
- /// at java.net.URL.<init>(URL.java:330)
- /// at jcifs.smb.SmbFile.<init>(SmbFile.java:355)
- /// ...
- /// </pre><blockquote>
- /// </remarks>
- public static void RegisterSmbURLHandler()
- {
- throw new NotImplementedException();
- }
-
- // supress javadoc constructor summary by removing 'protected'
- /// <summary>Set the default properties of the static Properties used by <tt>Config</tt>.
- /// </summary>
- /// <remarks>
- /// Set the default properties of the static Properties used by <tt>Config</tt>. This permits
- /// a different Properties object/file to be used as the source of properties for
- /// use by the jCIFS library. The Properties must be set <i>before jCIFS
- /// classes are accessed</i> as most jCIFS classes load properties statically once.
- /// Using this method will also override properties loaded
- /// using the <tt>-Djcifs.properties=</tt> commandline parameter.
- /// </remarks>
- public static void SetProperties(Properties prp)
- {
- Config._prp = new Properties(prp);
- try
- {
- Config._prp.PutAll(Runtime.GetProperties());
- }
- catch (SecurityException)
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("SecurityException: jcifs will ignore System properties");
- }
- }
- }
-
- /// <summary>
- /// Load the <code>Config</code> with properties from the stream
- /// <code>in</code> from a <code>Properties</code> file.
- /// </summary>
- /// <remarks>
- /// Load the <code>Config</code> with properties from the stream
- /// <code>in</code> from a <code>Properties</code> file.
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public static void Load(InputStream input)
- {
- if (input != null)
- {
- _prp.Load(input);
- }
- try
- {
- _prp.PutAll(Runtime.GetProperties());
- }
- catch (SecurityException)
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("SecurityException: jcifs will ignore System properties");
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static void Store(OutputStream output, string header)
- {
- _prp.Store(output);
- }
-
- /// <summary>Add a property.</summary>
- /// <remarks>Add a property.</remarks>
- public static void SetProperty(string key, string value)
- {
- _prp.SetProperty(key, value);
- }
-
- /// <summary>Retrieve a property as an <code>Object</code>.</summary>
- /// <remarks>Retrieve a property as an <code>Object</code>.</remarks>
- public static object Get(string key)
- {
- return _prp.GetProperty(key);
- }
-
- /// <summary>Retrieve a <code>String</code>.</summary>
- /// <remarks>
- /// Retrieve a <code>String</code>. If the key cannot be found,
- /// the provided <code>def</code> default parameter will be returned.
- /// </remarks>
- public static string GetProperty(string key, string def)
- {
- return (string)_prp.GetProperty(key, def);
- }
-
- /// <summary>Retrieve a <code>String</code>.</summary>
- /// <remarks>Retrieve a <code>String</code>. If the property is not found, <code>null</code> is returned.
- /// </remarks>
- public static string GetProperty(string key)
- {
- return (string)_prp.GetProperty(key);
- }
-
- /// <summary>Retrieve an <code>int</code>.</summary>
- /// <remarks>
- /// Retrieve an <code>int</code>. If the key does not exist or
- /// cannot be converted to an <code>int</code>, the provided default
- /// argument will be returned.
- /// </remarks>
- public static int GetInt(string key, int def)
- {
- string s = (string)_prp.GetProperty(key);
- if (s != null)
- {
- try
- {
- def = Convert.ToInt32(s);
- }
- catch (FormatException nfe)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(nfe, _log);
- }
- }
- }
- return def;
- }
-
- /// <summary>Retrieve an <code>int</code>.</summary>
- /// <remarks>Retrieve an <code>int</code>. If the property is not found, <code>-1</code> is returned.
- /// </remarks>
- public static int GetInt(string key)
- {
- string s = (string)_prp.GetProperty(key);
- int result = -1;
- if (s != null)
- {
- try
- {
- result = Convert.ToInt32(s);
- }
- catch (FormatException nfe)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(nfe, _log);
- }
- }
- }
- return result;
- }
-
- /// <summary>Retrieve a <code>long</code>.</summary>
- /// <remarks>
- /// Retrieve a <code>long</code>. If the key does not exist or
- /// cannot be converted to a <code>long</code>, the provided default
- /// argument will be returned.
- /// </remarks>
- public static long GetLong(string key, long def)
- {
- string s = (string)_prp.GetProperty(key);
- if (s != null)
- {
- try
- {
- def = long.Parse(s);
- }
- catch (FormatException nfe)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(nfe, _log);
- }
- }
- }
- return def;
- }
-
- /// <summary>Retrieve an <code>InetAddress</code>.</summary>
- /// <remarks>
- /// Retrieve an <code>InetAddress</code>. If the address is not
- /// an IP address and cannot be resolved <code>null</code> will
- /// be returned.
- /// </remarks>
- public static IPAddress GetInetAddress(string key, IPAddress def)
- {
- string addr = (string)_prp.GetProperty(key);
- if (addr != null)
- {
- try
- {
- def = Extensions.GetAddressByName(addr);
- }
- catch (UnknownHostException uhe)
- {
- if (_log.Level > 0)
- {
- _log.WriteLine(addr);
- Runtime.PrintStackTrace(uhe, _log);
- }
- }
- }
- return def;
- }
-
- public static IPAddress GetLocalHost()
- {
- string addr = (string)_prp.GetProperty("jcifs.smb.client.laddr");
- if (addr != null)
- {
- try
- {
- return Extensions.GetAddressByName(addr);
- }
- catch (UnknownHostException uhe)
- {
- if (_log.Level > 0)
- {
- _log.WriteLine("Ignoring jcifs.smb.client.laddr address: " + addr);
- Runtime.PrintStackTrace(uhe, _log);
- }
- }
- }
- return null;
- }
-
- /// <summary>Retrieve a boolean value.</summary>
- /// <remarks>Retrieve a boolean value. If the property is not found, the value of <code>def</code> is returned.
- /// </remarks>
- public static bool GetBoolean(string key, bool def)
- {
- string b = GetProperty(key);
- if (b != null)
- {
- def = b.ToLower().Equals("true");
- }
- return def;
- }
-
- /// <summary>
- /// Retrieve an array of <tt>InetAddress</tt> created from a property
- /// value containting a <tt>delim</tt> separated list of hostnames and/or
- /// ipaddresses.
- /// </summary>
- /// <remarks>
- /// Retrieve an array of <tt>InetAddress</tt> created from a property
- /// value containting a <tt>delim</tt> separated list of hostnames and/or
- /// ipaddresses.
- /// </remarks>
- public static IPAddress[] GetInetAddressArray(string key, string delim, IPAddress
- [] def)
- {
- string p = GetProperty(key);
- if (p != null)
- {
- StringTokenizer tok = new StringTokenizer(p, delim);
- int len = tok.CountTokens();
- IPAddress[] arr = new IPAddress[len];
- for (int i = 0; i < len; i++)
- {
- string addr = tok.NextToken();
- try
- {
- arr[i] = Extensions.GetAddressByName(addr);
- }
- catch (UnknownHostException uhe)
- {
- if (_log.Level > 0)
- {
- _log.WriteLine(addr);
- Runtime.PrintStackTrace(uhe, _log);
- }
- return def;
- }
- }
- return arr;
- }
- return def;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs
deleted file mode 100644
index 1d8d13c08..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-using SharpCifs.Util;
-
-namespace SharpCifs.Dcerpc
-{
- public class DcerpcBind : DcerpcMessage
- {
- internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED"
- , "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
- };
-
- internal static string GetResultMessage(int result)
- {
- return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4
- );
- }
-
- public override DcerpcException GetResult()
- {
- if (Result != 0)
- {
- return new DcerpcException(GetResultMessage(Result));
- }
- return null;
- }
-
- internal DcerpcBinding Binding;
-
- internal int MaxXmit;
-
- internal int MaxRecv;
-
- public DcerpcBind()
- {
- }
-
- internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle)
- {
- this.Binding = binding;
- MaxXmit = handle.MaxXmit;
- MaxRecv = handle.MaxRecv;
- Ptype = 11;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
-
- public override int GetOpnum()
- {
- return 0;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_short(MaxXmit);
- dst.Enc_ndr_short(MaxRecv);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_small(1);
- dst.Enc_ndr_small(0);
- dst.Enc_ndr_short(0);
- dst.Enc_ndr_short(0);
- dst.Enc_ndr_small(1);
- dst.Enc_ndr_small(0);
- Binding.Uuid.Encode(dst);
- dst.Enc_ndr_short(Binding.Major);
- dst.Enc_ndr_short(Binding.Minor);
- DcerpcConstants.DcerpcUuidSyntaxNdr.Encode(dst);
- dst.Enc_ndr_long(2);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- src.Dec_ndr_short();
- src.Dec_ndr_short();
- src.Dec_ndr_long();
- int n = src.Dec_ndr_short();
- src.Advance(n);
- src.Align(4);
- src.Dec_ndr_small();
- src.Align(4);
- Result = src.Dec_ndr_short();
- src.Dec_ndr_short();
- src.Advance(20);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs
deleted file mode 100644
index 234150664..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Dcerpc.Msrpc;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Dcerpc
-{
- public class DcerpcBinding
- {
- private static Hashtable _interfaces;
-
- static DcerpcBinding()
- {
- _interfaces = new Hashtable();
- _interfaces.Put("srvsvc", Srvsvc.GetSyntax());
- _interfaces.Put("lsarpc", Lsarpc.GetSyntax());
- _interfaces.Put("samr", Samr.GetSyntax());
- _interfaces.Put("netdfs", Netdfs.GetSyntax());
- }
-
- public static void AddInterface(string name, string syntax)
- {
- _interfaces.Put(name, syntax);
- }
-
- internal string Proto;
-
- internal string Server;
-
- internal string Endpoint;
-
- internal Hashtable Options;
-
- internal Uuid Uuid;
-
- internal int Major;
-
- internal int Minor;
-
- internal DcerpcBinding(string proto, string server)
- {
- this.Proto = proto;
- this.Server = server;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- internal virtual void SetOption(string key, object val)
- {
- if (key.Equals("endpoint"))
- {
- Endpoint = val.ToString().ToLower();
- if (Endpoint.StartsWith("\\pipe\\"))
- {
- string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
- if (iface != null)
- {
- int c;
- int p;
- c = iface.IndexOf(':');
- p = iface.IndexOf('.', c + 1);
- Uuid = new Uuid(Runtime.Substring(iface, 0, c));
- Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
- Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
- return;
- }
- }
- throw new DcerpcException("Bad endpoint: " + Endpoint);
- }
- if (Options == null)
- {
- Options = new Hashtable();
- }
- Options.Put(key, val);
- }
-
- internal virtual object GetOption(string key)
- {
- if (key.Equals("endpoint"))
- {
- return Endpoint;
- }
- if (Options != null)
- {
- return Options.Get(key);
- }
- return null;
- }
-
- public override string ToString()
- {
- /* string ret = proto + ":" + server + "[" + endpoint;
- if (options != null)
- {
- Iterator iter = (Iterator) options.Keys.GetEnumerator();
- while (iter.HasNext())
- {
- object key = iter.Next();
- object val = options.Get(key);
- ret += "," + key + "=" + val;
- }
- }
- ret += "]";
- return ret; */
- return null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs
deleted file mode 100644
index 5b69c5c2e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc
-{
- public static class DcerpcConstants
- {
- public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"
- );
-
- public static int DcerpcFirstFrag = unchecked(0x01);
-
- public static int DcerpcLastFrag = unchecked(0x02);
-
- public static int DcerpcPendingCancel = unchecked(0x04);
-
- public static int DcerpcReserved1 = unchecked(0x08);
-
- public static int DcerpcConcMpx = unchecked(0x10);
-
- public static int DcerpcDidNotExecute = unchecked(0x20);
-
- public static int DcerpcMaybe = unchecked(0x40);
-
- public static int DcerpcObjectUuid = unchecked(0x80);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs
deleted file mode 100644
index 55c061065..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc
-{
- public static class DcerpcError
- {
- public static int DcerpcFaultOther = unchecked(0x00000001);
-
- public static int DcerpcFaultAccessDenied = unchecked(0x00000005);
-
- public static int DcerpcFaultCantPerform = unchecked(0x000006D8);
-
- public static int DcerpcFaultNdr = unchecked(0x000006F7);
-
- public static int DcerpcFaultInvalidTag = unchecked(0x1C000006);
-
- public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A);
-
- public static int DcerpcFaultOpRngError = unchecked(0x1C010002);
-
- public static int DcerpcFaultUnkIf = unchecked(0x1C010003);
-
- public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
-
- public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied
- , DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch
- , DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError };
-
- public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER"
- , "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR",
- "DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR"
- , "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" };
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs
deleted file mode 100644
index 13c4f0d0c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Dcerpc
-{
-
- public class DcerpcException : IOException
- {
- internal static string GetMessageByDcerpcError(int errcode)
- {
- int min = 0;
- int max = DcerpcError.DcerpcFaultCodes.Length;
- while (max >= min)
- {
- int mid = (min + max) / 2;
- if (errcode > DcerpcError.DcerpcFaultCodes[mid])
- {
- min = mid + 1;
- }
- else
- {
- if (errcode < DcerpcError.DcerpcFaultCodes[mid])
- {
- max = mid - 1;
- }
- else
- {
- return DcerpcError.DcerpcFaultMessages[mid];
- }
- }
- }
- return "0x" + Hexdump.ToHexString(errcode, 8);
- }
-
- private int _error;
-
- private Exception _rootCause;
-
- internal DcerpcException(int error) : base(GetMessageByDcerpcError(error))
- {
- this._error = error;
- }
-
- public DcerpcException(string msg) : base(msg)
- {
- }
-
- public DcerpcException(string msg, Exception rootCause) : base(msg)
- {
- this._rootCause = rootCause;
- }
-
- public virtual int GetErrorCode()
- {
- return _error;
- }
-
- public virtual Exception GetRootCause()
- {
- return _rootCause;
- }
-
- public override string ToString()
- {
- if (_rootCause != null)
- {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- Runtime.PrintStackTrace(_rootCause, pw);
- return base.ToString() + "\n" + sw;
- }
- return base.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs
deleted file mode 100644
index 786b0ac12..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs
+++ /dev/null
@@ -1,332 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Dcerpc.Ndr;
-using SharpCifs.Smb;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Dcerpc
-{
- public abstract class DcerpcHandle
- {
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- protected internal static DcerpcBinding ParseBinding(string str)
- {
- int state;
- int mark;
- int si;
- char[] arr = str.ToCharArray();
- string proto = null;
- string key = null;
- DcerpcBinding binding = null;
- state = mark = si = 0;
- do
- {
- char ch = arr[si];
- switch (state)
- {
- case 0:
- {
- if (ch == ':')
- {
- proto = Runtime.Substring(str, mark, si);
- mark = si + 1;
- state = 1;
- }
- break;
- }
-
- case 1:
- {
- if (ch == '\\')
- {
- mark = si + 1;
- break;
- }
- state = 2;
- goto case 2;
- }
-
- case 2:
- {
- if (ch == '[')
- {
- string server = Runtime.Substring(str, mark, si).Trim();
- if (server.Length == 0)
- {
- server = "127.0.0.1";
- }
- binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si));
- mark = si + 1;
- state = 5;
- }
- break;
- }
-
- case 5:
- {
- if (ch == '=')
- {
- key = Runtime.Substring(str, mark, si).Trim();
- mark = si + 1;
- }
- else
- {
- if (ch == ',' || ch == ']')
- {
- string val = Runtime.Substring(str, mark, si).Trim();
- if (key == null)
- {
- key = "endpoint";
- }
- binding.SetOption(key, val);
- key = null;
- }
- }
- break;
- }
-
- default:
- {
- si = arr.Length;
- break;
- }
- }
- si++;
- }
- while (si < arr.Length);
- if (binding == null || binding.Endpoint == null)
- {
- throw new DcerpcException("Invalid binding URL: " + str);
- }
- return binding;
- }
-
- protected internal DcerpcBinding Binding;
-
- protected internal int MaxXmit = 4280;
-
- protected internal int MaxRecv;
-
- protected internal int State;
-
- protected internal IDcerpcSecurityProvider SecurityProvider;
-
- private static int _callId = 1;
-
- /// <exception cref="UnknownHostException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth)
- {
- if (url.StartsWith("ncacn_np:"))
- {
- return new DcerpcPipeHandle(url, auth);
- }
- throw new DcerpcException("DCERPC transport not supported: " + url);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Bind()
- {
- lock (this)
- {
- try
- {
- State = 1;
- DcerpcMessage bind = new DcerpcBind(Binding, this);
- Sendrecv(bind);
- }
- catch (IOException ioe)
- {
- State = 0;
- throw;
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Sendrecv(DcerpcMessage msg)
- {
- byte[] stub;
- byte[] frag;
- NdrBuffer buf;
- NdrBuffer fbuf;
- bool isLast;
- bool isDirect;
- DcerpcException de;
- if (State == 0)
- {
- Bind();
- }
- isDirect = true;
- stub = BufferCache.GetBuffer();
- try
- {
- int off;
- int tot;
- int n;
- buf = new NdrBuffer(stub, 0);
- msg.Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- msg.CallId = _callId++;
- msg.Encode(buf);
- if (SecurityProvider != null)
- {
- buf.SetIndex(0);
- SecurityProvider.Wrap(buf);
- }
- tot = buf.GetLength() - 24;
- off = 0;
- while (off < tot)
- {
- n = tot - off;
- if ((24 + n) > MaxXmit)
- {
- msg.Flags &= ~DcerpcConstants.DcerpcLastFrag;
- n = MaxXmit - 24;
- }
- else
- {
- msg.Flags |= DcerpcConstants.DcerpcLastFrag;
- isDirect = false;
- msg.AllocHint = n;
- }
- msg.Length = 24 + n;
- if (off > 0)
- {
- msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
- }
- if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag |
- DcerpcConstants.DcerpcLastFrag))
- {
- buf.Start = off;
- buf.Reset();
- msg.Encode_header(buf);
- buf.Enc_ndr_long(msg.AllocHint);
- buf.Enc_ndr_short(0);
- buf.Enc_ndr_short(msg.GetOpnum());
- }
- DoSendFragment(stub, off, msg.Length, isDirect);
- off += n;
- }
- DoReceiveFragment(stub, isDirect);
- buf.Reset();
- buf.SetIndex(8);
- buf.SetLength(buf.Dec_ndr_short());
- if (SecurityProvider != null)
- {
- SecurityProvider.Unwrap(buf);
- }
- buf.SetIndex(0);
- msg.Decode_header(buf);
- off = 24;
- if (msg.Ptype == 2 && msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
- {
- off = msg.Length;
- }
- frag = null;
- fbuf = null;
- while (msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
- {
- int stubFragLen;
- if (frag == null)
- {
- frag = new byte[MaxRecv];
- fbuf = new NdrBuffer(frag, 0);
- }
- DoReceiveFragment(frag, isDirect);
- fbuf.Reset();
- fbuf.SetIndex(8);
- fbuf.SetLength(fbuf.Dec_ndr_short());
- if (SecurityProvider != null)
- {
- SecurityProvider.Unwrap(fbuf);
- }
- fbuf.Reset();
- msg.Decode_header(fbuf);
- stubFragLen = msg.Length - 24;
- if ((off + stubFragLen) > stub.Length)
- {
- // shouldn't happen if alloc_hint is correct or greater
- byte[] tmp = new byte[off + stubFragLen];
- Array.Copy(stub, 0, tmp, 0, off);
- stub = tmp;
- }
- Array.Copy(frag, 24, stub, off, stubFragLen);
- off += stubFragLen;
- }
- buf = new NdrBuffer(stub, 0);
- msg.Decode(buf);
- }
- finally
- {
- BufferCache.ReleaseBuffer(stub);
- }
- if ((de = msg.GetResult()) != null)
- {
- throw de;
- }
- }
-
- public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider
- )
- {
- this.SecurityProvider = securityProvider;
- }
-
- public virtual string GetServer()
- {
- if (this is DcerpcPipeHandle)
- {
- return ((DcerpcPipeHandle)this).Pipe.GetServer();
- }
- return null;
- }
-
- public virtual Principal GetPrincipal()
- {
- if (this is DcerpcPipeHandle)
- {
- return ((DcerpcPipeHandle)this).Pipe.GetPrincipal();
- }
- return null;
- }
-
- public override string ToString()
- {
- return Binding.ToString();
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoSendFragment(byte[] buf, int off, int length,
- bool isDirect);
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect);
-
- /// <exception cref="System.IO.IOException"></exception>
- public abstract void Close();
-
- public DcerpcHandle()
- {
- MaxRecv = MaxXmit;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs
deleted file mode 100644
index 543dd72dd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc
-{
- public abstract class DcerpcMessage : NdrObject
- {
- protected internal int Ptype = -1;
-
- protected internal int Flags;
-
- protected internal int Length;
-
- protected internal int CallId;
-
- protected internal int AllocHint;
-
- protected internal int Result;
-
- public virtual bool IsFlagSet(int flag)
- {
- return (Flags & flag) == flag;
- }
-
- public virtual void UnsetFlag(int flag)
- {
- Flags &= ~flag;
- }
-
- public virtual void SetFlag(int flag)
- {
- Flags |= flag;
- }
-
- public virtual DcerpcException GetResult()
- {
- if (Result != 0)
- {
- return new DcerpcException(Result);
- }
- return null;
- }
-
- internal virtual void Encode_header(NdrBuffer buf)
- {
- buf.Enc_ndr_small(5);
- buf.Enc_ndr_small(0);
- buf.Enc_ndr_small(Ptype);
- buf.Enc_ndr_small(Flags);
- buf.Enc_ndr_long(unchecked(0x00000010));
- buf.Enc_ndr_short(Length);
- buf.Enc_ndr_short(0);
- buf.Enc_ndr_long(CallId);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- internal virtual void Decode_header(NdrBuffer buf)
- {
- if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0)
- {
- throw new NdrException("DCERPC version not supported");
- }
- Ptype = buf.Dec_ndr_small();
- Flags = buf.Dec_ndr_small();
- if (buf.Dec_ndr_long() != unchecked(0x00000010))
- {
- throw new NdrException("Data representation not supported");
- }
- Length = buf.Dec_ndr_short();
- if (buf.Dec_ndr_short() != 0)
- {
- throw new NdrException("DCERPC authentication not supported");
- }
- CallId = buf.Dec_ndr_long();
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer buf)
- {
- int start = buf.GetIndex();
- int allocHintIndex = 0;
- buf.Advance(16);
- if (Ptype == 0)
- {
- allocHintIndex = buf.GetIndex();
- buf.Enc_ndr_long(0);
- buf.Enc_ndr_short(0);
- buf.Enc_ndr_short(GetOpnum());
- }
- Encode_in(buf);
- Length = buf.GetIndex() - start;
- if (Ptype == 0)
- {
- buf.SetIndex(allocHintIndex);
- AllocHint = Length - allocHintIndex;
- buf.Enc_ndr_long(AllocHint);
- }
- buf.SetIndex(start);
- Encode_header(buf);
- buf.SetIndex(start + Length);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer buf)
- {
- Decode_header(buf);
- if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13)
- {
- throw new NdrException("Unexpected ptype: " + Ptype);
- }
- if (Ptype == 2 || Ptype == 3)
- {
- AllocHint = buf.Dec_ndr_long();
- buf.Dec_ndr_short();
- buf.Dec_ndr_short();
- }
- if (Ptype == 3 || Ptype == 13)
- {
- Result = buf.Dec_ndr_long();
- }
- else
- {
- Decode_out(buf);
- }
- }
-
- public abstract int GetOpnum();
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public abstract void Encode_in(NdrBuffer dst);
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public abstract void Decode_out(NdrBuffer src);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs
deleted file mode 100644
index 0399578cd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Smb;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Dcerpc
-{
- public class DcerpcPipeHandle : DcerpcHandle
- {
- internal SmbNamedPipe Pipe;
-
- internal SmbFileInputStream In;
-
- internal SmbFileOutputStream Out;
-
- internal bool IsStart = true;
-
- /// <exception cref="UnknownHostException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
- {
- Binding = ParseBinding(url);
- url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint
- , 6);
- string @params = string.Empty;
- string server;
- string address;
- server = (string)Binding.GetOption("server");
- if (server != null)
- {
- @params += "&server=" + server;
- }
- address = (string)Binding.GetOption("address");
- if (server != null)
- {
- @params += "&address=" + address;
- }
- if (@params.Length > 0)
- {
- url += "?" + Runtime.Substring(@params, 1);
- }
- Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr
- | SmbNamedPipe.PipeTypeDceTransact, auth);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoSendFragment(byte[] buf, int off, int length,
- bool isDirect)
- {
- if (Out != null && Out.IsOpen() == false)
- {
- throw new IOException("DCERPC pipe is no longer open");
- }
- if (In == null)
- {
- In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream();
- }
- if (Out == null)
- {
- Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream();
- }
- if (isDirect)
- {
- Out.WriteDirect(buf, off, length, 1);
- return;
- }
- Out.Write(buf, off, length);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoReceiveFragment(byte[] buf, bool isDirect)
- {
- int off;
- int flags;
- int length;
- if (buf.Length < MaxRecv)
- {
- throw new ArgumentException("buffer too small");
- }
- if (IsStart && !isDirect)
- {
- // start of new frag, do trans
- off = In.Read(buf, 0, 1024);
- }
- else
- {
- off = In.ReadDirect(buf, 0, buf.Length);
- }
- if (buf[0] != 5 && buf[1] != 0)
- {
- throw new IOException("Unexpected DCERPC PDU header");
- }
- flags = buf[3] & unchecked(0xFF);
- // next read is start of new frag
- IsStart = (flags & DcerpcConstants.DcerpcLastFrag) == DcerpcConstants.DcerpcLastFrag;
- length = Encdec.Dec_uint16le(buf, 8);
- if (length > MaxRecv)
- {
- throw new IOException("Unexpected fragment length: " + length);
- }
- while (off < length)
- {
- off += In.ReadDirect(buf, off, length - off);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override void Close()
- {
- State = 0;
- if (Out != null)
- {
- Out.Close();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs
deleted file mode 100644
index cc46902f1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc
-{
- public interface IDcerpcSecurityProvider
- {
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- void Wrap(NdrBuffer outgoing);
-
- /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
- void Unwrap(NdrBuffer incoming);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs
deleted file mode 100644
index 03964fcc7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class LsaPolicyHandle : Rpc.PolicyHandle
- {
- /// <exception cref="System.IO.IOException"></exception>
- public LsaPolicyHandle(DcerpcHandle handle, string server, int access)
- {
- if (server == null)
- {
- server = "\\\\";
- }
- MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this);
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Close()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs
deleted file mode 100644
index ef09bb16e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- internal class LsarSidArrayX : Lsarpc.LsarSidArray
- {
- internal LsarSidArrayX(Sid[] sids)
- {
- NumSids = sids.Length;
- this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
- for (int si = 0; si < sids.Length; si++)
- {
- this.Sids[si] = new Lsarpc.LsarSidPtr();
- this.Sids[si].Sid = sids[si];
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs
deleted file mode 100644
index 1ae85c473..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs
+++ /dev/null
@@ -1,1161 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class Lsarpc
- {
- public static string GetSyntax()
- {
- return "12345778-1234-abcd-ef00-0123456789ab:0.0";
- }
-
- public class LsarQosInfo : NdrObject
- {
- public int Length;
-
- public short ImpersonationLevel;
-
- public byte ContextMode;
-
- public byte EffectiveOnly;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Length);
- dst.Enc_ndr_short(ImpersonationLevel);
- dst.Enc_ndr_small(ContextMode);
- dst.Enc_ndr_small(EffectiveOnly);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Length = src.Dec_ndr_long();
- ImpersonationLevel = (short)src.Dec_ndr_short();
- ContextMode = unchecked((byte)src.Dec_ndr_small());
- EffectiveOnly = unchecked((byte)src.Dec_ndr_small());
- }
- }
-
- public class LsarObjectAttributes : NdrObject
- {
- public int Length;
-
- public NdrSmall RootDirectory;
-
- public Rpc.Unicode_string ObjectName;
-
- public int Attributes;
-
- public int SecurityDescriptor;
-
- public LsarQosInfo SecurityQualityOfService;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Length);
- dst.Enc_ndr_referent(RootDirectory, 1);
- dst.Enc_ndr_referent(ObjectName, 1);
- dst.Enc_ndr_long(Attributes);
- dst.Enc_ndr_long(SecurityDescriptor);
- dst.Enc_ndr_referent(SecurityQualityOfService, 1);
- if (RootDirectory != null)
- {
- dst = dst.Deferred;
- RootDirectory.Encode(dst);
- }
- if (ObjectName != null)
- {
- dst = dst.Deferred;
- ObjectName.Encode(dst);
- }
- if (SecurityQualityOfService != null)
- {
- dst = dst.Deferred;
- SecurityQualityOfService.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Length = src.Dec_ndr_long();
- int rootDirectoryp = src.Dec_ndr_long();
- int objectNamep = src.Dec_ndr_long();
- Attributes = src.Dec_ndr_long();
- SecurityDescriptor = src.Dec_ndr_long();
- int securityQualityOfServicep = src.Dec_ndr_long();
- if (rootDirectoryp != 0)
- {
- src = src.Deferred;
- RootDirectory.Decode(src);
- }
- if (objectNamep != 0)
- {
- if (ObjectName == null)
- {
- ObjectName = new Rpc.Unicode_string();
- }
- src = src.Deferred;
- ObjectName.Decode(src);
- }
- if (securityQualityOfServicep != 0)
- {
- if (SecurityQualityOfService == null)
- {
- SecurityQualityOfService = new LsarQosInfo();
- }
- src = src.Deferred;
- SecurityQualityOfService.Decode(src);
- }
- }
- }
-
- public class LsarDomainInfo : NdrObject
- {
- public Rpc.Unicode_string Name;
-
- public Rpc.SidT Sid;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(Name.Length);
- dst.Enc_ndr_short(Name.MaximumLength);
- dst.Enc_ndr_referent(Name.Buffer, 1);
- dst.Enc_ndr_referent(Sid, 1);
- if (Name.Buffer != null)
- {
- dst = dst.Deferred;
- int nameBufferl = Name.Length / 2;
- int nameBuffers = Name.MaximumLength / 2;
- dst.Enc_ndr_long(nameBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(nameBufferl);
- int nameBufferi = dst.Index;
- dst.Advance(2 * nameBufferl);
- dst = dst.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- dst.Enc_ndr_short(Name.Buffer[i]);
- }
- }
- if (Sid != null)
- {
- dst = dst.Deferred;
- Sid.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- src.Align(4);
- if (Name == null)
- {
- Name = new Rpc.Unicode_string();
- }
- Name.Length = (short)src.Dec_ndr_short();
- Name.MaximumLength = (short)src.Dec_ndr_short();
- int nameBufferp = src.Dec_ndr_long();
- int sidp = src.Dec_ndr_long();
- if (nameBufferp != 0)
- {
- src = src.Deferred;
- int nameBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int nameBufferl = src.Dec_ndr_long();
- int nameBufferi = src.Index;
- src.Advance(2 * nameBufferl);
- if (Name.Buffer == null)
- {
- if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Name.Buffer = new short[nameBuffers];
- }
- src = src.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- Name.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- if (sidp != 0)
- {
- if (Sid == null)
- {
- Sid = new Rpc.SidT();
- }
- src = src.Deferred;
- Sid.Decode(src);
- }
- }
- }
-
- public class LsarDnsDomainInfo : NdrObject
- {
- public Rpc.Unicode_string Name;
-
- public Rpc.Unicode_string DnsDomain;
-
- public Rpc.Unicode_string DnsForest;
-
- public Rpc.UuidT DomainGuid;
-
- public Rpc.SidT Sid;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(Name.Length);
- dst.Enc_ndr_short(Name.MaximumLength);
- dst.Enc_ndr_referent(Name.Buffer, 1);
- dst.Enc_ndr_short(DnsDomain.Length);
- dst.Enc_ndr_short(DnsDomain.MaximumLength);
- dst.Enc_ndr_referent(DnsDomain.Buffer, 1);
- dst.Enc_ndr_short(DnsForest.Length);
- dst.Enc_ndr_short(DnsForest.MaximumLength);
- dst.Enc_ndr_referent(DnsForest.Buffer, 1);
- dst.Enc_ndr_long(DomainGuid.TimeLow);
- dst.Enc_ndr_short(DomainGuid.TimeMid);
- dst.Enc_ndr_short(DomainGuid.TimeHiAndVersion);
- dst.Enc_ndr_small(DomainGuid.ClockSeqHiAndReserved);
- dst.Enc_ndr_small(DomainGuid.ClockSeqLow);
- int domainGuidNodes = 6;
- int domainGuidNodei = dst.Index;
- dst.Advance(1 * domainGuidNodes);
- dst.Enc_ndr_referent(Sid, 1);
- if (Name.Buffer != null)
- {
- dst = dst.Deferred;
- int nameBufferl = Name.Length / 2;
- int nameBuffers = Name.MaximumLength / 2;
- dst.Enc_ndr_long(nameBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(nameBufferl);
- int nameBufferi = dst.Index;
- dst.Advance(2 * nameBufferl);
- dst = dst.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- dst.Enc_ndr_short(Name.Buffer[i]);
- }
- }
- if (DnsDomain.Buffer != null)
- {
- dst = dst.Deferred;
- int dnsDomainBufferl = DnsDomain.Length / 2;
- int dnsDomainBuffers = DnsDomain.MaximumLength / 2;
- dst.Enc_ndr_long(dnsDomainBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(dnsDomainBufferl);
- int dnsDomainBufferi = dst.Index;
- dst.Advance(2 * dnsDomainBufferl);
- dst = dst.Derive(dnsDomainBufferi);
- for (int i = 0; i < dnsDomainBufferl; i++)
- {
- dst.Enc_ndr_short(DnsDomain.Buffer[i]);
- }
- }
- if (DnsForest.Buffer != null)
- {
- dst = dst.Deferred;
- int dnsForestBufferl = DnsForest.Length / 2;
- int dnsForestBuffers = DnsForest.MaximumLength / 2;
- dst.Enc_ndr_long(dnsForestBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(dnsForestBufferl);
- int dnsForestBufferi = dst.Index;
- dst.Advance(2 * dnsForestBufferl);
- dst = dst.Derive(dnsForestBufferi);
- for (int i = 0; i < dnsForestBufferl; i++)
- {
- dst.Enc_ndr_short(DnsForest.Buffer[i]);
- }
- }
- dst = dst.Derive(domainGuidNodei);
- for (int i1 = 0; i1 < domainGuidNodes; i1++)
- {
- dst.Enc_ndr_small(DomainGuid.Node[i1]);
- }
- if (Sid != null)
- {
- dst = dst.Deferred;
- Sid.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- src.Align(4);
- if (Name == null)
- {
- Name = new Rpc.Unicode_string();
- }
- Name.Length = (short)src.Dec_ndr_short();
- Name.MaximumLength = (short)src.Dec_ndr_short();
- int nameBufferp = src.Dec_ndr_long();
- src.Align(4);
- if (DnsDomain == null)
- {
- DnsDomain = new Rpc.Unicode_string();
- }
- DnsDomain.Length = (short)src.Dec_ndr_short();
- DnsDomain.MaximumLength = (short)src.Dec_ndr_short();
- int dnsDomainBufferp = src.Dec_ndr_long();
- src.Align(4);
- if (DnsForest == null)
- {
- DnsForest = new Rpc.Unicode_string();
- }
- DnsForest.Length = (short)src.Dec_ndr_short();
- DnsForest.MaximumLength = (short)src.Dec_ndr_short();
- int dnsForestBufferp = src.Dec_ndr_long();
- src.Align(4);
- if (DomainGuid == null)
- {
- DomainGuid = new Rpc.UuidT();
- }
- DomainGuid.TimeLow = src.Dec_ndr_long();
- DomainGuid.TimeMid = (short)src.Dec_ndr_short();
- DomainGuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
- DomainGuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
- DomainGuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
- int domainGuidNodes = 6;
- int domainGuidNodei = src.Index;
- src.Advance(1 * domainGuidNodes);
- int sidp = src.Dec_ndr_long();
- if (nameBufferp != 0)
- {
- src = src.Deferred;
- int nameBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int nameBufferl = src.Dec_ndr_long();
- int nameBufferi = src.Index;
- src.Advance(2 * nameBufferl);
- if (Name.Buffer == null)
- {
- if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Name.Buffer = new short[nameBuffers];
- }
- src = src.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- Name.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- if (dnsDomainBufferp != 0)
- {
- src = src.Deferred;
- int dnsDomainBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int dnsDomainBufferl = src.Dec_ndr_long();
- int dnsDomainBufferi = src.Index;
- src.Advance(2 * dnsDomainBufferl);
- if (DnsDomain.Buffer == null)
- {
- if (dnsDomainBuffers < 0 || dnsDomainBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- DnsDomain.Buffer = new short[dnsDomainBuffers];
- }
- src = src.Derive(dnsDomainBufferi);
- for (int i = 0; i < dnsDomainBufferl; i++)
- {
- DnsDomain.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- if (dnsForestBufferp != 0)
- {
- src = src.Deferred;
- int dnsForestBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int dnsForestBufferl = src.Dec_ndr_long();
- int dnsForestBufferi = src.Index;
- src.Advance(2 * dnsForestBufferl);
- if (DnsForest.Buffer == null)
- {
- if (dnsForestBuffers < 0 || dnsForestBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- DnsForest.Buffer = new short[dnsForestBuffers];
- }
- src = src.Derive(dnsForestBufferi);
- for (int i = 0; i < dnsForestBufferl; i++)
- {
- DnsForest.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- if (DomainGuid.Node == null)
- {
- if (domainGuidNodes < 0 || domainGuidNodes > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- DomainGuid.Node = new byte[domainGuidNodes];
- }
- src = src.Derive(domainGuidNodei);
- for (int i1 = 0; i1 < domainGuidNodes; i1++)
- {
- DomainGuid.Node[i1] = unchecked((byte)src.Dec_ndr_small());
- }
- if (sidp != 0)
- {
- if (Sid == null)
- {
- Sid = new Rpc.SidT();
- }
- src = src.Deferred;
- Sid.Decode(src);
- }
- }
- }
-
- public const int PolicyInfoAuditEvents = 2;
-
- public const int PolicyInfoPrimaryDomain = 3;
-
- public const int PolicyInfoAccountDomain = 5;
-
- public const int PolicyInfoServerRole = 6;
-
- public const int PolicyInfoModification = 9;
-
- public const int PolicyInfoDnsDomain = 12;
-
- public class LsarSidPtr : NdrObject
- {
- public Rpc.SidT Sid;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(Sid, 1);
- if (Sid != null)
- {
- dst = dst.Deferred;
- Sid.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int sidp = src.Dec_ndr_long();
- if (sidp != 0)
- {
- if (Sid == null)
- {
- Sid = new Rpc.SidT();
- }
- src = src.Deferred;
- Sid.Decode(src);
- }
- }
- }
-
- public class LsarSidArray : NdrObject
- {
- public int NumSids;
-
- public LsarSidPtr[] Sids;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(NumSids);
- dst.Enc_ndr_referent(Sids, 1);
- if (Sids != null)
- {
- dst = dst.Deferred;
- int sidss = NumSids;
- dst.Enc_ndr_long(sidss);
- int sidsi = dst.Index;
- dst.Advance(4 * sidss);
- dst = dst.Derive(sidsi);
- for (int i = 0; i < sidss; i++)
- {
- Sids[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- NumSids = src.Dec_ndr_long();
- int sidsp = src.Dec_ndr_long();
- if (sidsp != 0)
- {
- src = src.Deferred;
- int sidss = src.Dec_ndr_long();
- int sidsi = src.Index;
- src.Advance(4 * sidss);
- if (Sids == null)
- {
- if (sidss < 0 || sidss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Sids = new LsarSidPtr[sidss];
- }
- src = src.Derive(sidsi);
- for (int i = 0; i < sidss; i++)
- {
- if (Sids[i] == null)
- {
- Sids[i] = new LsarSidPtr();
- }
- Sids[i].Decode(src);
- }
- }
- }
- }
-
- public const int SidNameUseNone = 0;
-
- public const int SidNameUser = 1;
-
- public const int SidNameDomGrp = 2;
-
- public const int SidNameDomain = 3;
-
- public const int SidNameAlias = 4;
-
- public const int SidNameWknGrp = 5;
-
- public const int SidNameDeleted = 6;
-
- public const int SidNameInvalid = 7;
-
- public const int SidNameUnknown = 8;
-
- public class LsarTranslatedSid : NdrObject
- {
- public int SidType;
-
- public int Rid;
-
- public int SidIndex;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(SidType);
- dst.Enc_ndr_long(Rid);
- dst.Enc_ndr_long(SidIndex);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- SidType = src.Dec_ndr_short();
- Rid = src.Dec_ndr_long();
- SidIndex = src.Dec_ndr_long();
- }
- }
-
- public class LsarTransSidArray : NdrObject
- {
- public int Count;
-
- public LsarTranslatedSid[] Sids;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Sids, 1);
- if (Sids != null)
- {
- dst = dst.Deferred;
- int sidss = Count;
- dst.Enc_ndr_long(sidss);
- int sidsi = dst.Index;
- dst.Advance(12 * sidss);
- dst = dst.Derive(sidsi);
- for (int i = 0; i < sidss; i++)
- {
- Sids[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int sidsp = src.Dec_ndr_long();
- if (sidsp != 0)
- {
- src = src.Deferred;
- int sidss = src.Dec_ndr_long();
- int sidsi = src.Index;
- src.Advance(12 * sidss);
- if (Sids == null)
- {
- if (sidss < 0 || sidss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Sids = new LsarTranslatedSid[sidss];
- }
- src = src.Derive(sidsi);
- for (int i = 0; i < sidss; i++)
- {
- if (Sids[i] == null)
- {
- Sids[i] = new LsarTranslatedSid();
- }
- Sids[i].Decode(src);
- }
- }
- }
- }
-
- public class LsarTrustInformation : NdrObject
- {
- public Rpc.Unicode_string Name;
-
- public Rpc.SidT Sid;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(Name.Length);
- dst.Enc_ndr_short(Name.MaximumLength);
- dst.Enc_ndr_referent(Name.Buffer, 1);
- dst.Enc_ndr_referent(Sid, 1);
- if (Name.Buffer != null)
- {
- dst = dst.Deferred;
- int nameBufferl = Name.Length / 2;
- int nameBuffers = Name.MaximumLength / 2;
- dst.Enc_ndr_long(nameBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(nameBufferl);
- int nameBufferi = dst.Index;
- dst.Advance(2 * nameBufferl);
- dst = dst.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- dst.Enc_ndr_short(Name.Buffer[i]);
- }
- }
- if (Sid != null)
- {
- dst = dst.Deferred;
- Sid.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- src.Align(4);
- if (Name == null)
- {
- Name = new Rpc.Unicode_string();
- }
- Name.Length = (short)src.Dec_ndr_short();
- Name.MaximumLength = (short)src.Dec_ndr_short();
- int nameBufferp = src.Dec_ndr_long();
- int sidp = src.Dec_ndr_long();
- if (nameBufferp != 0)
- {
- src = src.Deferred;
- int nameBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int nameBufferl = src.Dec_ndr_long();
- int nameBufferi = src.Index;
- src.Advance(2 * nameBufferl);
- if (Name.Buffer == null)
- {
- if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Name.Buffer = new short[nameBuffers];
- }
- src = src.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- Name.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- if (sidp != 0)
- {
- if (Sid == null)
- {
- Sid = new Rpc.SidT();
- }
- src = src.Deferred;
- Sid.Decode(src);
- }
- }
- }
-
- public class LsarRefDomainList : NdrObject
- {
- public int Count;
-
- public LsarTrustInformation[] Domains;
-
- public int MaxCount;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Domains, 1);
- dst.Enc_ndr_long(MaxCount);
- if (Domains != null)
- {
- dst = dst.Deferred;
- int domainss = Count;
- dst.Enc_ndr_long(domainss);
- int domainsi = dst.Index;
- dst.Advance(12 * domainss);
- dst = dst.Derive(domainsi);
- for (int i = 0; i < domainss; i++)
- {
- Domains[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int domainsp = src.Dec_ndr_long();
- MaxCount = src.Dec_ndr_long();
- if (domainsp != 0)
- {
- src = src.Deferred;
- int domainss = src.Dec_ndr_long();
- int domainsi = src.Index;
- src.Advance(12 * domainss);
- if (Domains == null)
- {
- if (domainss < 0 || domainss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Domains = new LsarTrustInformation[domainss];
- }
- src = src.Derive(domainsi);
- for (int i = 0; i < domainss; i++)
- {
- if (Domains[i] == null)
- {
- Domains[i] = new LsarTrustInformation();
- }
- Domains[i].Decode(src);
- }
- }
- }
- }
-
- public class LsarTranslatedName : NdrObject
- {
- public short SidType;
-
- public Rpc.Unicode_string Name;
-
- public int SidIndex;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(SidType);
- dst.Enc_ndr_short(Name.Length);
- dst.Enc_ndr_short(Name.MaximumLength);
- dst.Enc_ndr_referent(Name.Buffer, 1);
- dst.Enc_ndr_long(SidIndex);
- if (Name.Buffer != null)
- {
- dst = dst.Deferred;
- int nameBufferl = Name.Length / 2;
- int nameBuffers = Name.MaximumLength / 2;
- dst.Enc_ndr_long(nameBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(nameBufferl);
- int nameBufferi = dst.Index;
- dst.Advance(2 * nameBufferl);
- dst = dst.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- dst.Enc_ndr_short(Name.Buffer[i]);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- SidType = (short)src.Dec_ndr_short();
- src.Align(4);
- if (Name == null)
- {
- Name = new Rpc.Unicode_string();
- }
- Name.Length = (short)src.Dec_ndr_short();
- Name.MaximumLength = (short)src.Dec_ndr_short();
- int nameBufferp = src.Dec_ndr_long();
- SidIndex = src.Dec_ndr_long();
- if (nameBufferp != 0)
- {
- src = src.Deferred;
- int nameBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int nameBufferl = src.Dec_ndr_long();
- int nameBufferi = src.Index;
- src.Advance(2 * nameBufferl);
- if (Name.Buffer == null)
- {
- if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Name.Buffer = new short[nameBuffers];
- }
- src = src.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- Name.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- }
- }
-
- public class LsarTransNameArray : NdrObject
- {
- public int Count;
-
- public LsarTranslatedName[] Names;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Names, 1);
- if (Names != null)
- {
- dst = dst.Deferred;
- int namess = Count;
- dst.Enc_ndr_long(namess);
- int namesi = dst.Index;
- dst.Advance(16 * namess);
- dst = dst.Derive(namesi);
- for (int i = 0; i < namess; i++)
- {
- Names[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int namesp = src.Dec_ndr_long();
- if (namesp != 0)
- {
- src = src.Deferred;
- int namess = src.Dec_ndr_long();
- int namesi = src.Index;
- src.Advance(16 * namess);
- if (Names == null)
- {
- if (namess < 0 || namess > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Names = new LsarTranslatedName[namess];
- }
- src = src.Derive(namesi);
- for (int i = 0; i < namess; i++)
- {
- if (Names[i] == null)
- {
- Names[i] = new LsarTranslatedName();
- }
- Names[i].Decode(src);
- }
- }
- }
- }
-
- public class LsarClose : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x00);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public LsarClose(Rpc.PolicyHandle handle)
- {
- this.Handle = handle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Handle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class LsarQueryInformationPolicy : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x07);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public short Level;
-
- public NdrObject Info;
-
- public LsarQueryInformationPolicy(Rpc.PolicyHandle handle, short level, NdrObject
- info)
- {
- this.Handle = handle;
- this.Level = level;
- this.Info = info;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- dst.Enc_ndr_short(Level);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- src.Dec_ndr_short();
- Info.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class LsarLookupSids : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x0f);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public LsarSidArray Sids;
-
- public LsarRefDomainList Domains;
-
- public LsarTransNameArray Names;
-
- public short Level;
-
- public int Count;
-
- public LsarLookupSids(Rpc.PolicyHandle handle, LsarSidArray sids, LsarRefDomainList
- domains, LsarTransNameArray names, short level, int count)
- {
- this.Handle = handle;
- this.Sids = sids;
- this.Domains = domains;
- this.Names = names;
- this.Level = level;
- this.Count = count;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- Sids.Encode(dst);
- Names.Encode(dst);
- dst.Enc_ndr_short(Level);
- dst.Enc_ndr_long(Count);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- int domainsp = src.Dec_ndr_long();
- if (domainsp != 0)
- {
- if (Domains == null)
- {
- Domains = new LsarRefDomainList();
- }
- Domains.Decode(src);
- }
- Names.Decode(src);
- Count = src.Dec_ndr_long();
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class LsarOpenPolicy2 : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x2c);
- }
-
- public int Retval;
-
- public string SystemName;
-
- public LsarObjectAttributes ObjectAttributes;
-
- public int DesiredAccess;
-
- public Rpc.PolicyHandle PolicyHandle;
-
- public LsarOpenPolicy2(string systemName, LsarObjectAttributes objectAttributes
- , int desiredAccess, Rpc.PolicyHandle policyHandle)
- {
- this.SystemName = systemName;
- this.ObjectAttributes = objectAttributes;
- this.DesiredAccess = desiredAccess;
- this.PolicyHandle = policyHandle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(SystemName, 1);
- if (SystemName != null)
- {
- dst.Enc_ndr_string(SystemName);
- }
- ObjectAttributes.Encode(dst);
- dst.Enc_ndr_long(DesiredAccess);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- PolicyHandle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class LsarQueryInformationPolicy2 : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x2e);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public short Level;
-
- public NdrObject Info;
-
- public LsarQueryInformationPolicy2(Rpc.PolicyHandle handle, short level, NdrObject
- info)
- {
- this.Handle = handle;
- this.Level = level;
- this.Info = info;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- dst.Enc_ndr_short(Level);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- src.Dec_ndr_short();
- Info.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs
deleted file mode 100644
index 6a9d4302a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
- {
- public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
- {
- Info.Level = Level;
- Info.E = new Netdfs.DfsEnumArray200();
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
-
- public virtual IFileEntry[] GetEntries()
- {
- Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
- SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
- for (int i = 0; i < a200.Count; i++)
- {
- entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
- }
- return entries;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs
deleted file mode 100644
index d9c0afb34..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain
- {
- public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags
- , Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0)
- {
- this.Sam = sam;
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs
deleted file mode 100644
index 77b2ee375..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias
- {
- public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids
- ) : base(aliasHandle, sids)
- {
- this.Sids = sids;
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs
deleted file mode 100644
index 0aaf31026..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcLookupSids : Lsarpc.LsarLookupSids
- {
- internal Sid[] sids;
-
- public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle
- , new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray
- (), 1, sids.Length)
- {
- this.sids = sids;
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs
deleted file mode 100644
index 9d2c2a0f4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
- {
- public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle
- ) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle)
- {
- ObjectAttributes.Length = 24;
- Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();
- qos.Length = 12;
- qos.ImpersonationLevel = 2;
- qos.ContextMode = 1;
- qos.EffectiveOnly = 0;
- ObjectAttributes.SecurityQualityOfService = qos;
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs
deleted file mode 100644
index 820d81ab2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy
- {
- public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject
- info) : base(policyHandle, level, info)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs
deleted file mode 100644
index 80c45257c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcSamrConnect2 : Samr.SamrConnect2
- {
- public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle
- ) : base(server, access, policyHandle)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs
deleted file mode 100644
index 0f2603e9c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcSamrConnect4 : Samr.SamrConnect4
- {
- public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle
- ) : base(server, 2, access, policyHandle)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs
deleted file mode 100644
index e0b9b68d3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
- {
- public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle
- aliasHandle) : base(handle, access, rid, aliasHandle)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs
deleted file mode 100644
index 2ac6bceed..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain
- {
- public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle
- domainHandle) : base(handle, access, sid, domainHandle)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs
deleted file mode 100644
index 7c7b64abf..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcShareEnum : Srvsvc.ShareEnumAll
- {
- internal class MsrpcShareInfo1 : SmbShareInfo
- {
- internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1)
- {
- this._enclosing = enclosing;
- NetName = info1.Netname;
- Type = info1.Type;
- Remark = info1.Remark;
- }
-
- private readonly MsrpcShareEnum _enclosing;
- }
-
- public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1
- (), -1, 0, 0)
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
-
- public virtual IFileEntry[] GetEntries()
- {
- Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info;
- MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr
- .Count];
- for (int i = 0; i < ctr.Count; i++)
- {
- entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]);
- }
- return entries;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs
deleted file mode 100644
index 802ed61a3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
- {
- public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename
- , 502, new Srvsvc.ShareInfo502())
- {
- Ptype = 0;
- Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual Ace[] GetSecurity()
- {
- Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
- if (info502.SecurityDescriptor != null)
- {
- SecurityDescriptor sd;
- sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
- return sd.Aces;
- }
- return null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs
deleted file mode 100644
index a338b2885..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs
+++ /dev/null
@@ -1,616 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class Netdfs
- {
- public static string GetSyntax()
- {
- return "4fc742e0-4a10-11cf-8273-00aa004ae673:3.0";
- }
-
- public const int DfsVolumeFlavorStandalone = unchecked(0x100);
-
- public const int DfsVolumeFlavorAdBlob = unchecked(0x200);
-
- public const int DfsStorageStateOffline = unchecked(0x0001);
-
- public const int DfsStorageStateOnline = unchecked(0x0002);
-
- public const int DfsStorageStateActive = unchecked(0x0004);
-
- public class DfsInfo1 : NdrObject
- {
- public string EntryPath;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(EntryPath, 1);
- if (EntryPath != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(EntryPath);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int entryPathp = src.Dec_ndr_long();
- if (entryPathp != 0)
- {
- src = src.Deferred;
- EntryPath = src.Dec_ndr_string();
- }
- }
- }
-
- public class DfsEnumArray1 : NdrObject
- {
- public int Count;
-
- public DfsInfo1[] S;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(S, 1);
- if (S != null)
- {
- dst = dst.Deferred;
- int ss = Count;
- dst.Enc_ndr_long(ss);
- int si = dst.Index;
- dst.Advance(4 * ss);
- dst = dst.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- S[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int sp = src.Dec_ndr_long();
- if (sp != 0)
- {
- src = src.Deferred;
- int ss = src.Dec_ndr_long();
- int si = src.Index;
- src.Advance(4 * ss);
- if (S == null)
- {
- if (ss < 0 || ss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- S = new DfsInfo1[ss];
- }
- src = src.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- if (S[i] == null)
- {
- S[i] = new DfsInfo1();
- }
- S[i].Decode(src);
- }
- }
- }
- }
-
- public class DfsStorageInfo : NdrObject
- {
- public int State;
-
- public string ServerName;
-
- public string ShareName;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(State);
- dst.Enc_ndr_referent(ServerName, 1);
- dst.Enc_ndr_referent(ShareName, 1);
- if (ServerName != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(ServerName);
- }
- if (ShareName != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(ShareName);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- State = src.Dec_ndr_long();
- int serverNamep = src.Dec_ndr_long();
- int shareNamep = src.Dec_ndr_long();
- if (serverNamep != 0)
- {
- src = src.Deferred;
- ServerName = src.Dec_ndr_string();
- }
- if (shareNamep != 0)
- {
- src = src.Deferred;
- ShareName = src.Dec_ndr_string();
- }
- }
- }
-
- public class DfsInfo3 : NdrObject
- {
- public string Path;
-
- public string Comment;
-
- public int State;
-
- public int NumStores;
-
- public DfsStorageInfo[] Stores;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(Path, 1);
- dst.Enc_ndr_referent(Comment, 1);
- dst.Enc_ndr_long(State);
- dst.Enc_ndr_long(NumStores);
- dst.Enc_ndr_referent(Stores, 1);
- if (Path != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Path);
- }
- if (Comment != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Comment);
- }
- if (Stores != null)
- {
- dst = dst.Deferred;
- int storess = NumStores;
- dst.Enc_ndr_long(storess);
- int storesi = dst.Index;
- dst.Advance(12 * storess);
- dst = dst.Derive(storesi);
- for (int i = 0; i < storess; i++)
- {
- Stores[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int pathp = src.Dec_ndr_long();
- int commentp = src.Dec_ndr_long();
- State = src.Dec_ndr_long();
- NumStores = src.Dec_ndr_long();
- int storesp = src.Dec_ndr_long();
- if (pathp != 0)
- {
- src = src.Deferred;
- Path = src.Dec_ndr_string();
- }
- if (commentp != 0)
- {
- src = src.Deferred;
- Comment = src.Dec_ndr_string();
- }
- if (storesp != 0)
- {
- src = src.Deferred;
- int storess = src.Dec_ndr_long();
- int storesi = src.Index;
- src.Advance(12 * storess);
- if (Stores == null)
- {
- if (storess < 0 || storess > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Stores = new DfsStorageInfo[storess];
- }
- src = src.Derive(storesi);
- for (int i = 0; i < storess; i++)
- {
- if (Stores[i] == null)
- {
- Stores[i] = new DfsStorageInfo();
- }
- Stores[i].Decode(src);
- }
- }
- }
- }
-
- public class DfsEnumArray3 : NdrObject
- {
- public int Count;
-
- public DfsInfo3[] S;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(S, 1);
- if (S != null)
- {
- dst = dst.Deferred;
- int ss = Count;
- dst.Enc_ndr_long(ss);
- int si = dst.Index;
- dst.Advance(20 * ss);
- dst = dst.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- S[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int sp = src.Dec_ndr_long();
- if (sp != 0)
- {
- src = src.Deferred;
- int ss = src.Dec_ndr_long();
- int si = src.Index;
- src.Advance(20 * ss);
- if (S == null)
- {
- if (ss < 0 || ss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- S = new DfsInfo3[ss];
- }
- src = src.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- if (S[i] == null)
- {
- S[i] = new DfsInfo3();
- }
- S[i].Decode(src);
- }
- }
- }
- }
-
- public class DfsInfo200 : NdrObject
- {
- public string DfsName;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(DfsName, 1);
- if (DfsName != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(DfsName);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int dfsNamep = src.Dec_ndr_long();
- if (dfsNamep != 0)
- {
- src = src.Deferred;
- DfsName = src.Dec_ndr_string();
- }
- }
- }
-
- public class DfsEnumArray200 : NdrObject
- {
- public int Count;
-
- public DfsInfo200[] S;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(S, 1);
- if (S != null)
- {
- dst = dst.Deferred;
- int ss = Count;
- dst.Enc_ndr_long(ss);
- int si = dst.Index;
- dst.Advance(4 * ss);
- dst = dst.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- S[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int sp = src.Dec_ndr_long();
- if (sp != 0)
- {
- src = src.Deferred;
- int ss = src.Dec_ndr_long();
- int si = src.Index;
- src.Advance(4 * ss);
- if (S == null)
- {
- if (ss < 0 || ss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- S = new DfsInfo200[ss];
- }
- src = src.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- if (S[i] == null)
- {
- S[i] = new DfsInfo200();
- }
- S[i].Decode(src);
- }
- }
- }
- }
-
- public class DfsInfo300 : NdrObject
- {
- public int Flags;
-
- public string DfsName;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Flags);
- dst.Enc_ndr_referent(DfsName, 1);
- if (DfsName != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(DfsName);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Flags = src.Dec_ndr_long();
- int dfsNamep = src.Dec_ndr_long();
- if (dfsNamep != 0)
- {
- src = src.Deferred;
- DfsName = src.Dec_ndr_string();
- }
- }
- }
-
- public class DfsEnumArray300 : NdrObject
- {
- public int Count;
-
- public DfsInfo300[] S;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(S, 1);
- if (S != null)
- {
- dst = dst.Deferred;
- int ss = Count;
- dst.Enc_ndr_long(ss);
- int si = dst.Index;
- dst.Advance(8 * ss);
- dst = dst.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- S[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int sp = src.Dec_ndr_long();
- if (sp != 0)
- {
- src = src.Deferred;
- int ss = src.Dec_ndr_long();
- int si = src.Index;
- src.Advance(8 * ss);
- if (S == null)
- {
- if (ss < 0 || ss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- S = new DfsInfo300[ss];
- }
- src = src.Derive(si);
- for (int i = 0; i < ss; i++)
- {
- if (S[i] == null)
- {
- S[i] = new DfsInfo300();
- }
- S[i].Decode(src);
- }
- }
- }
- }
-
- public class DfsEnumStruct : NdrObject
- {
- public int Level;
-
- public NdrObject E;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Level);
- int descr = Level;
- dst.Enc_ndr_long(descr);
- dst.Enc_ndr_referent(E, 1);
- if (E != null)
- {
- dst = dst.Deferred;
- E.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Level = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int ep = src.Dec_ndr_long();
- if (ep != 0)
- {
- if (E == null)
- {
- E = new DfsEnumArray1();
- }
- src = src.Deferred;
- E.Decode(src);
- }
- }
- }
-
- public class NetrDfsEnumEx : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x15);
- }
-
- public int Retval;
-
- public string DfsName;
-
- public int Level;
-
- public int Prefmaxlen;
-
- public DfsEnumStruct Info;
-
- public NdrLong Totalentries;
-
- public NetrDfsEnumEx(string dfsName, int level, int prefmaxlen, DfsEnumStruct
- info, NdrLong totalentries)
- {
- this.DfsName = dfsName;
- this.Level = level;
- this.Prefmaxlen = prefmaxlen;
- this.Info = info;
- this.Totalentries = totalentries;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_string(DfsName);
- dst.Enc_ndr_long(Level);
- dst.Enc_ndr_long(Prefmaxlen);
- dst.Enc_ndr_referent(Info, 1);
- if (Info != null)
- {
- Info.Encode(dst);
- }
- dst.Enc_ndr_referent(Totalentries, 1);
- if (Totalentries != null)
- {
- Totalentries.Encode(dst);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- if (Info == null)
- {
- Info = new DfsEnumStruct();
- }
- Info.Decode(src);
- }
- int totalentriesp = src.Dec_ndr_long();
- if (totalentriesp != 0)
- {
- Totalentries.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs
deleted file mode 100644
index bdc71695e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs
+++ /dev/null
@@ -1,579 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class Samr
- {
- public static string GetSyntax()
- {
- return "12345778-1234-abcd-ef00-0123456789ac:1.0";
- }
-
- public const int AcbDisabled = 1;
-
- public const int AcbHomdirreq = 2;
-
- public const int AcbPwnotreq = 4;
-
- public const int AcbTempdup = 8;
-
- public const int AcbNormal = 16;
-
- public const int AcbMns = 32;
-
- public const int AcbDomtrust = 64;
-
- public const int AcbWstrust = 128;
-
- public const int AcbSvrtrust = 256;
-
- public const int AcbPwnoexp = 512;
-
- public const int AcbAutolock = 1024;
-
- public const int AcbEncTxtPwdAllowed = 2048;
-
- public const int AcbSmartcardRequired = 4096;
-
- public const int AcbTrustedForDelegation = 8192;
-
- public const int AcbNotDelegated = 16384;
-
- public const int AcbUseDesKeyOnly = 32768;
-
- public const int AcbDontRequirePreauth = 65536;
-
- public class SamrCloseHandle : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x01);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public SamrCloseHandle(Rpc.PolicyHandle handle)
- {
- this.Handle = handle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrConnect2 : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x39);
- }
-
- public int Retval;
-
- public string SystemName;
-
- public int AccessMask;
-
- public Rpc.PolicyHandle Handle;
-
- public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle
- )
- {
- this.SystemName = systemName;
- this.AccessMask = accessMask;
- this.Handle = handle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(SystemName, 1);
- if (SystemName != null)
- {
- dst.Enc_ndr_string(SystemName);
- }
- dst.Enc_ndr_long(AccessMask);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Handle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrConnect4 : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x3e);
- }
-
- public int Retval;
-
- public string SystemName;
-
- public int Unknown;
-
- public int AccessMask;
-
- public Rpc.PolicyHandle Handle;
-
- public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle
- handle)
- {
- this.SystemName = systemName;
- this.Unknown = unknown;
- this.AccessMask = accessMask;
- this.Handle = handle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(SystemName, 1);
- if (SystemName != null)
- {
- dst.Enc_ndr_string(SystemName);
- }
- dst.Enc_ndr_long(Unknown);
- dst.Enc_ndr_long(AccessMask);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Handle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrOpenDomain : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x07);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle Handle;
-
- public int AccessMask;
-
- public Rpc.SidT Sid;
-
- public Rpc.PolicyHandle DomainHandle;
-
- public SamrOpenDomain(Rpc.PolicyHandle handle, int accessMask, Rpc.SidT sid, Rpc.PolicyHandle
- domainHandle)
- {
- this.Handle = handle;
- this.AccessMask = accessMask;
- this.Sid = sid;
- this.DomainHandle = domainHandle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- Handle.Encode(dst);
- dst.Enc_ndr_long(AccessMask);
- Sid.Encode(dst);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- DomainHandle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrSamEntry : NdrObject
- {
- public int Idx;
-
- public Rpc.Unicode_string Name;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Idx);
- dst.Enc_ndr_short(Name.Length);
- dst.Enc_ndr_short(Name.MaximumLength);
- dst.Enc_ndr_referent(Name.Buffer, 1);
- if (Name.Buffer != null)
- {
- dst = dst.Deferred;
- int nameBufferl = Name.Length / 2;
- int nameBuffers = Name.MaximumLength / 2;
- dst.Enc_ndr_long(nameBuffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(nameBufferl);
- int nameBufferi = dst.Index;
- dst.Advance(2 * nameBufferl);
- dst = dst.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- dst.Enc_ndr_short(Name.Buffer[i]);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Idx = src.Dec_ndr_long();
- src.Align(4);
- if (Name == null)
- {
- Name = new Rpc.Unicode_string();
- }
- Name.Length = (short)src.Dec_ndr_short();
- Name.MaximumLength = (short)src.Dec_ndr_short();
- int nameBufferp = src.Dec_ndr_long();
- if (nameBufferp != 0)
- {
- src = src.Deferred;
- int nameBuffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int nameBufferl = src.Dec_ndr_long();
- int nameBufferi = src.Index;
- src.Advance(2 * nameBufferl);
- if (Name.Buffer == null)
- {
- if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Name.Buffer = new short[nameBuffers];
- }
- src = src.Derive(nameBufferi);
- for (int i = 0; i < nameBufferl; i++)
- {
- Name.Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- }
- }
-
- public class SamrSamArray : NdrObject
- {
- public int Count;
-
- public SamrSamEntry[] Entries;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Entries, 1);
- if (Entries != null)
- {
- dst = dst.Deferred;
- int entriess = Count;
- dst.Enc_ndr_long(entriess);
- int entriesi = dst.Index;
- dst.Advance(12 * entriess);
- dst = dst.Derive(entriesi);
- for (int i = 0; i < entriess; i++)
- {
- Entries[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int entriesp = src.Dec_ndr_long();
- if (entriesp != 0)
- {
- src = src.Deferred;
- int entriess = src.Dec_ndr_long();
- int entriesi = src.Index;
- src.Advance(12 * entriess);
- if (Entries == null)
- {
- if (entriess < 0 || entriess > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Entries = new SamrSamEntry[entriess];
- }
- src = src.Derive(entriesi);
- for (int i = 0; i < entriess; i++)
- {
- if (Entries[i] == null)
- {
- Entries[i] = new SamrSamEntry();
- }
- Entries[i].Decode(src);
- }
- }
- }
- }
-
- public class SamrEnumerateAliasesInDomain : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x0f);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle DomainHandle;
-
- public int ResumeHandle;
-
- public int AcctFlags;
-
- public SamrSamArray Sam;
-
- public int NumEntries;
-
- public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, int resumeHandle
- , int acctFlags, SamrSamArray sam, int numEntries)
- {
- this.DomainHandle = domainHandle;
- this.ResumeHandle = resumeHandle;
- this.AcctFlags = acctFlags;
- this.Sam = sam;
- this.NumEntries = numEntries;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- DomainHandle.Encode(dst);
- dst.Enc_ndr_long(ResumeHandle);
- dst.Enc_ndr_long(AcctFlags);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- ResumeHandle = src.Dec_ndr_long();
- int samp = src.Dec_ndr_long();
- if (samp != 0)
- {
- if (Sam == null)
- {
- Sam = new SamrSamArray();
- }
- Sam.Decode(src);
- }
- NumEntries = src.Dec_ndr_long();
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrOpenAlias : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x1b);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle DomainHandle;
-
- public int AccessMask;
-
- public int Rid;
-
- public Rpc.PolicyHandle AliasHandle;
-
- public SamrOpenAlias(Rpc.PolicyHandle domainHandle, int accessMask, int rid, Rpc.PolicyHandle
- aliasHandle)
- {
- this.DomainHandle = domainHandle;
- this.AccessMask = accessMask;
- this.Rid = rid;
- this.AliasHandle = aliasHandle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- DomainHandle.Encode(dst);
- dst.Enc_ndr_long(AccessMask);
- dst.Enc_ndr_long(Rid);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- AliasHandle.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class SamrGetMembersInAlias : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x21);
- }
-
- public int Retval;
-
- public Rpc.PolicyHandle AliasHandle;
-
- public Lsarpc.LsarSidArray Sids;
-
- public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray
- sids)
- {
- this.AliasHandle = aliasHandle;
- this.Sids = sids;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- AliasHandle.Encode(dst);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Sids.Decode(src);
- Retval = src.Dec_ndr_long();
- }
- }
-
- public const int SeGroupMandatory = 1;
-
- public const int SeGroupEnabledByDefault = 2;
-
- public const int SeGroupEnabled = 4;
-
- public const int SeGroupOwner = 8;
-
- public const int SeGroupUseForDenyOnly = 16;
-
- public const int SeGroupResource = 536870912;
-
- public const int SeGroupLogonId = -1073741824;
-
- public class SamrRidWithAttribute : NdrObject
- {
- public int Rid;
-
- public int Attributes;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Rid);
- dst.Enc_ndr_long(Attributes);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Rid = src.Dec_ndr_long();
- Attributes = src.Dec_ndr_long();
- }
- }
-
- public class SamrRidWithAttributeArray : NdrObject
- {
- public int Count;
-
- public SamrRidWithAttribute[] Rids;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Rids, 1);
- if (Rids != null)
- {
- dst = dst.Deferred;
- int ridss = Count;
- dst.Enc_ndr_long(ridss);
- int ridsi = dst.Index;
- dst.Advance(8 * ridss);
- dst = dst.Derive(ridsi);
- for (int i = 0; i < ridss; i++)
- {
- Rids[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int ridsp = src.Dec_ndr_long();
- if (ridsp != 0)
- {
- src = src.Deferred;
- int ridss = src.Dec_ndr_long();
- int ridsi = src.Index;
- src.Advance(8 * ridss);
- if (Rids == null)
- {
- if (ridss < 0 || ridss > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Rids = new SamrRidWithAttribute[ridss];
- }
- src = src.Derive(ridsi);
- for (int i = 0; i < ridss; i++)
- {
- if (Rids[i] == null)
- {
- Rids[i] = new SamrRidWithAttribute();
- }
- Rids[i].Decode(src);
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs
deleted file mode 100644
index d4ebdacc4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class SamrAliasHandle : Rpc.PolicyHandle
- {
- /// <exception cref="System.IO.IOException"></exception>
- public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access
- , int rid)
- {
- MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Close()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs
deleted file mode 100644
index d44c79886..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Smb;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class SamrDomainHandle : Rpc.PolicyHandle
- {
- /// <exception cref="System.IO.IOException"></exception>
- public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access
- , Rpc.SidT sid)
- {
- MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this
- );
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Close()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs
deleted file mode 100644
index 0cd3f9369..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class SamrPolicyHandle : Rpc.PolicyHandle
- {
- /// <exception cref="System.IO.IOException"></exception>
- public SamrPolicyHandle(DcerpcHandle handle, string server, int access)
- {
- if (server == null)
- {
- server = "\\\\";
- }
- MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this);
- try
- {
- handle.Sendrecv(rpc);
- }
- catch (DcerpcException de)
- {
- if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError)
- {
- throw;
- }
- MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this);
- handle.Sendrecv(rpc2);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Close()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs
deleted file mode 100644
index f33f48327..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs
+++ /dev/null
@@ -1,734 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc.Msrpc
-{
- public class Srvsvc
- {
- public static string GetSyntax()
- {
- return "4b324fc8-1670-01d3-1278-5a47bf6ee188:3.0";
- }
-
- public class ShareInfo0 : NdrObject
- {
- public string Netname;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(Netname, 1);
- if (Netname != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Netname);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int netnamep = src.Dec_ndr_long();
- if (netnamep != 0)
- {
- src = src.Deferred;
- Netname = src.Dec_ndr_string();
- }
- }
- }
-
- public class ShareInfoCtr0 : NdrObject
- {
- public int Count;
-
- public ShareInfo0[] Array;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Array, 1);
- if (Array != null)
- {
- dst = dst.Deferred;
- int arrays = Count;
- dst.Enc_ndr_long(arrays);
- int arrayi = dst.Index;
- dst.Advance(4 * arrays);
- dst = dst.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- Array[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int arrayp = src.Dec_ndr_long();
- if (arrayp != 0)
- {
- src = src.Deferred;
- int arrays = src.Dec_ndr_long();
- int arrayi = src.Index;
- src.Advance(4 * arrays);
- if (Array == null)
- {
- if (arrays < 0 || arrays > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Array = new ShareInfo0[arrays];
- }
- src = src.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- if (Array[i] == null)
- {
- Array[i] = new ShareInfo0();
- }
- Array[i].Decode(src);
- }
- }
- }
- }
-
- public class ShareInfo1 : NdrObject
- {
- public string Netname;
-
- public int Type;
-
- public string Remark;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(Netname, 1);
- dst.Enc_ndr_long(Type);
- dst.Enc_ndr_referent(Remark, 1);
- if (Netname != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Netname);
- }
- if (Remark != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Remark);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int netnamep = src.Dec_ndr_long();
- Type = src.Dec_ndr_long();
- int remarkp = src.Dec_ndr_long();
- if (netnamep != 0)
- {
- src = src.Deferred;
- Netname = src.Dec_ndr_string();
- }
- if (remarkp != 0)
- {
- src = src.Deferred;
- Remark = src.Dec_ndr_string();
- }
- }
- }
-
- public class ShareInfoCtr1 : NdrObject
- {
- public int Count;
-
- public ShareInfo1[] Array;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Array, 1);
- if (Array != null)
- {
- dst = dst.Deferred;
- int arrays = Count;
- dst.Enc_ndr_long(arrays);
- int arrayi = dst.Index;
- dst.Advance(12 * arrays);
- dst = dst.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- Array[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int arrayp = src.Dec_ndr_long();
- if (arrayp != 0)
- {
- src = src.Deferred;
- int arrays = src.Dec_ndr_long();
- int arrayi = src.Index;
- src.Advance(12 * arrays);
- if (Array == null)
- {
- if (arrays < 0 || arrays > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Array = new ShareInfo1[arrays];
- }
- src = src.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- if (Array[i] == null)
- {
- Array[i] = new ShareInfo1();
- }
- Array[i].Decode(src);
- }
- }
- }
- }
-
- public class ShareInfo502 : NdrObject
- {
- public string Netname;
-
- public int Type;
-
- public string Remark;
-
- public int Permissions;
-
- public int MaxUses;
-
- public int CurrentUses;
-
- public string Path;
-
- public string Password;
-
- public int SdSize;
-
- public byte[] SecurityDescriptor;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_referent(Netname, 1);
- dst.Enc_ndr_long(Type);
- dst.Enc_ndr_referent(Remark, 1);
- dst.Enc_ndr_long(Permissions);
- dst.Enc_ndr_long(MaxUses);
- dst.Enc_ndr_long(CurrentUses);
- dst.Enc_ndr_referent(Path, 1);
- dst.Enc_ndr_referent(Password, 1);
- dst.Enc_ndr_long(SdSize);
- dst.Enc_ndr_referent(SecurityDescriptor, 1);
- if (Netname != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Netname);
- }
- if (Remark != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Remark);
- }
- if (Path != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Path);
- }
- if (Password != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Password);
- }
- if (SecurityDescriptor != null)
- {
- dst = dst.Deferred;
- int securityDescriptors = SdSize;
- dst.Enc_ndr_long(securityDescriptors);
- int securityDescriptori = dst.Index;
- dst.Advance(1 * securityDescriptors);
- dst = dst.Derive(securityDescriptori);
- for (int i = 0; i < securityDescriptors; i++)
- {
- dst.Enc_ndr_small(SecurityDescriptor[i]);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int netnamep = src.Dec_ndr_long();
- Type = src.Dec_ndr_long();
- int remarkp = src.Dec_ndr_long();
- Permissions = src.Dec_ndr_long();
- MaxUses = src.Dec_ndr_long();
- CurrentUses = src.Dec_ndr_long();
- int pathp = src.Dec_ndr_long();
- int passwordp = src.Dec_ndr_long();
- SdSize = src.Dec_ndr_long();
- int securityDescriptorp = src.Dec_ndr_long();
- if (netnamep != 0)
- {
- src = src.Deferred;
- Netname = src.Dec_ndr_string();
- }
- if (remarkp != 0)
- {
- src = src.Deferred;
- Remark = src.Dec_ndr_string();
- }
- if (pathp != 0)
- {
- src = src.Deferred;
- Path = src.Dec_ndr_string();
- }
- if (passwordp != 0)
- {
- src = src.Deferred;
- Password = src.Dec_ndr_string();
- }
- if (securityDescriptorp != 0)
- {
- src = src.Deferred;
- int securityDescriptors = src.Dec_ndr_long();
- int securityDescriptori = src.Index;
- src.Advance(1 * securityDescriptors);
- if (SecurityDescriptor == null)
- {
- if (securityDescriptors < 0 || securityDescriptors > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- SecurityDescriptor = new byte[securityDescriptors];
- }
- src = src.Derive(securityDescriptori);
- for (int i = 0; i < securityDescriptors; i++)
- {
- SecurityDescriptor[i] = unchecked((byte)src.Dec_ndr_small());
- }
- }
- }
- }
-
- public class ShareInfoCtr502 : NdrObject
- {
- public int Count;
-
- public ShareInfo502[] Array;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Count);
- dst.Enc_ndr_referent(Array, 1);
- if (Array != null)
- {
- dst = dst.Deferred;
- int arrays = Count;
- dst.Enc_ndr_long(arrays);
- int arrayi = dst.Index;
- dst.Advance(40 * arrays);
- dst = dst.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- Array[i].Encode(dst);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Count = src.Dec_ndr_long();
- int arrayp = src.Dec_ndr_long();
- if (arrayp != 0)
- {
- src = src.Deferred;
- int arrays = src.Dec_ndr_long();
- int arrayi = src.Index;
- src.Advance(40 * arrays);
- if (Array == null)
- {
- if (arrays < 0 || arrays > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Array = new ShareInfo502[arrays];
- }
- src = src.Derive(arrayi);
- for (int i = 0; i < arrays; i++)
- {
- if (Array[i] == null)
- {
- Array[i] = new ShareInfo502();
- }
- Array[i].Decode(src);
- }
- }
- }
- }
-
- public class ShareEnumAll : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x0f);
- }
-
- public int Retval;
-
- public string Servername;
-
- public int Level;
-
- public NdrObject Info;
-
- public int Prefmaxlen;
-
- public int Totalentries;
-
- public int ResumeHandle;
-
- public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen,
- int totalentries, int resumeHandle)
- {
- this.Servername = servername;
- this.Level = level;
- this.Info = info;
- this.Prefmaxlen = prefmaxlen;
- this.Totalentries = totalentries;
- this.ResumeHandle = resumeHandle;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(Servername, 1);
- if (Servername != null)
- {
- dst.Enc_ndr_string(Servername);
- }
- dst.Enc_ndr_long(Level);
- int descr = Level;
- dst.Enc_ndr_long(descr);
- dst.Enc_ndr_referent(Info, 1);
- if (Info != null)
- {
- dst = dst.Deferred;
- Info.Encode(dst);
- }
- dst.Enc_ndr_long(Prefmaxlen);
- dst.Enc_ndr_long(ResumeHandle);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- Level = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- if (Info == null)
- {
- Info = new ShareInfoCtr0();
- }
- src = src.Deferred;
- Info.Decode(src);
- }
- Totalentries = src.Dec_ndr_long();
- ResumeHandle = src.Dec_ndr_long();
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class ShareGetInfo : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x10);
- }
-
- public int Retval;
-
- public string Servername;
-
- public string Sharename;
-
- public int Level;
-
- public NdrObject Info;
-
- public ShareGetInfo(string servername, string sharename, int level, NdrObject info
- )
- {
- this.Servername = servername;
- this.Sharename = sharename;
- this.Level = level;
- this.Info = info;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(Servername, 1);
- if (Servername != null)
- {
- dst.Enc_ndr_string(Servername);
- }
- dst.Enc_ndr_string(Sharename);
- dst.Enc_ndr_long(Level);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- src.Dec_ndr_long();
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- if (Info == null)
- {
- Info = new ShareInfo0();
- }
- src = src.Deferred;
- Info.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class ServerInfo100 : NdrObject
- {
- public int PlatformId;
-
- public string Name;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(PlatformId);
- dst.Enc_ndr_referent(Name, 1);
- if (Name != null)
- {
- dst = dst.Deferred;
- dst.Enc_ndr_string(Name);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- PlatformId = src.Dec_ndr_long();
- int namep = src.Dec_ndr_long();
- if (namep != 0)
- {
- src = src.Deferred;
- Name = src.Dec_ndr_string();
- }
- }
- }
-
- public class ServerGetInfo : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x15);
- }
-
- public int Retval;
-
- public string Servername;
-
- public int Level;
-
- public NdrObject Info;
-
- public ServerGetInfo(string servername, int level, NdrObject info)
- {
- this.Servername = servername;
- this.Level = level;
- this.Info = info;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(Servername, 1);
- if (Servername != null)
- {
- dst.Enc_ndr_string(Servername);
- }
- dst.Enc_ndr_long(Level);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- src.Dec_ndr_long();
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- if (Info == null)
- {
- Info = new ServerInfo100();
- }
- src = src.Deferred;
- Info.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
-
- public class TimeOfDayInfo : NdrObject
- {
- public int Elapsedt;
-
- public int Msecs;
-
- public int Hours;
-
- public int Mins;
-
- public int Secs;
-
- public int Hunds;
-
- public int Timezone;
-
- public int Tinterval;
-
- public int Day;
-
- public int Month;
-
- public int Year;
-
- public int Weekday;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Elapsedt);
- dst.Enc_ndr_long(Msecs);
- dst.Enc_ndr_long(Hours);
- dst.Enc_ndr_long(Mins);
- dst.Enc_ndr_long(Secs);
- dst.Enc_ndr_long(Hunds);
- dst.Enc_ndr_long(Timezone);
- dst.Enc_ndr_long(Tinterval);
- dst.Enc_ndr_long(Day);
- dst.Enc_ndr_long(Month);
- dst.Enc_ndr_long(Year);
- dst.Enc_ndr_long(Weekday);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Elapsedt = src.Dec_ndr_long();
- Msecs = src.Dec_ndr_long();
- Hours = src.Dec_ndr_long();
- Mins = src.Dec_ndr_long();
- Secs = src.Dec_ndr_long();
- Hunds = src.Dec_ndr_long();
- Timezone = src.Dec_ndr_long();
- Tinterval = src.Dec_ndr_long();
- Day = src.Dec_ndr_long();
- Month = src.Dec_ndr_long();
- Year = src.Dec_ndr_long();
- Weekday = src.Dec_ndr_long();
- }
- }
-
- public class RemoteTod : DcerpcMessage
- {
- public override int GetOpnum()
- {
- return unchecked(0x1c);
- }
-
- public int Retval;
-
- public string Servername;
-
- public TimeOfDayInfo Info;
-
- public RemoteTod(string servername, TimeOfDayInfo info)
- {
- this.Servername = servername;
- this.Info = info;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode_in(NdrBuffer dst)
- {
- dst.Enc_ndr_referent(Servername, 1);
- if (Servername != null)
- {
- dst.Enc_ndr_string(Servername);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode_out(NdrBuffer src)
- {
- int infop = src.Dec_ndr_long();
- if (infop != 0)
- {
- if (Info == null)
- {
- Info = new TimeOfDayInfo();
- }
- Info.Decode(src);
- }
- Retval = src.Dec_ndr_long();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs
deleted file mode 100644
index 0a47de799..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs
+++ /dev/null
@@ -1,305 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Dcerpc.Ndr
-{
- public class NdrBuffer
- {
- internal int Referent;
-
- internal Hashtable Referents;
-
- internal class Entry
- {
- internal int Referent;
-
- internal object Obj;
- }
-
- public byte[] Buf;
-
- public int Start;
-
- public int Index;
-
- public int Length;
-
- public NdrBuffer Deferred;
-
- public NdrBuffer(byte[] buf, int start)
- {
- this.Buf = buf;
- this.Start = Index = start;
- Length = 0;
- Deferred = this;
- }
-
- public virtual NdrBuffer Derive(int idx)
- {
- NdrBuffer nb = new NdrBuffer(Buf, Start);
- nb.Index = idx;
- nb.Deferred = Deferred;
- return nb;
- }
-
- public virtual void Reset()
- {
- Index = Start;
- Length = 0;
- Deferred = this;
- }
-
- public virtual int GetIndex()
- {
- return Index;
- }
-
- public virtual void SetIndex(int index)
- {
- this.Index = index;
- }
-
- public virtual int GetCapacity()
- {
- return Buf.Length - Start;
- }
-
- public virtual int GetTailSpace()
- {
- return Buf.Length - Index;
- }
-
- public virtual byte[] GetBuffer()
- {
- return Buf;
- }
-
- public virtual int Align(int boundary, byte value)
- {
- int n = Align(boundary);
- int i = n;
- while (i > 0)
- {
- Buf[Index - i] = value;
- i--;
- }
- return n;
- }
-
- public virtual void WriteOctetArray(byte[] b, int i, int l)
- {
- Array.Copy(b, i, Buf, Index, l);
- Advance(l);
- }
-
- public virtual void ReadOctetArray(byte[] b, int i, int l)
- {
- Array.Copy(Buf, Index, b, i, l);
- Advance(l);
- }
-
- public virtual int GetLength()
- {
- return Deferred.Length;
- }
-
- public virtual void SetLength(int length)
- {
- Deferred.Length = length;
- }
-
- public virtual void Advance(int n)
- {
- Index += n;
- if ((Index - Start) > Deferred.Length)
- {
- Deferred.Length = Index - Start;
- }
- }
-
- public virtual int Align(int boundary)
- {
- int m = boundary - 1;
- int i = Index - Start;
- int n = ((i + m) & ~m) - i;
- Advance(n);
- return n;
- }
-
- public virtual void Enc_ndr_small(int s)
- {
- Buf[Index] = unchecked((byte)(s & unchecked(0xFF)));
- Advance(1);
- }
-
- public virtual int Dec_ndr_small()
- {
- int val = Buf[Index] & unchecked(0xFF);
- Advance(1);
- return val;
- }
-
- public virtual void Enc_ndr_short(int s)
- {
- Align(2);
- Encdec.Enc_uint16le((short)s, Buf, Index);
- Advance(2);
- }
-
- public virtual int Dec_ndr_short()
- {
- Align(2);
- int val = Encdec.Dec_uint16le(Buf, Index);
- Advance(2);
- return val;
- }
-
- public virtual void Enc_ndr_long(int l)
- {
- Align(4);
- Encdec.Enc_uint32le(l, Buf, Index);
- Advance(4);
- }
-
- public virtual int Dec_ndr_long()
- {
- Align(4);
- int val = Encdec.Dec_uint32le(Buf, Index);
- Advance(4);
- return val;
- }
-
- public virtual void Enc_ndr_hyper(long h)
- {
- Align(8);
- Encdec.Enc_uint64le(h, Buf, Index);
- Advance(8);
- }
-
- public virtual long Dec_ndr_hyper()
- {
- Align(8);
- long val = Encdec.Dec_uint64le(Buf, Index);
- Advance(8);
- return val;
- }
-
- public virtual void Enc_ndr_string(string s)
- {
- Align(4);
- int i = Index;
- int len = s.Length;
- Encdec.Enc_uint32le(len + 1, Buf, i);
- i += 4;
- Encdec.Enc_uint32le(0, Buf, i);
- i += 4;
- Encdec.Enc_uint32le(len + 1, Buf, i);
- i += 4;
- try
- {
- Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len
- * 2);
- }
- catch (UnsupportedEncodingException)
- {
- }
- i += len * 2;
- Buf[i++] = unchecked((byte)('\0'));
- Buf[i++] = unchecked((byte)('\0'));
- Advance(i - Index);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public virtual string Dec_ndr_string()
- {
- Align(4);
- int i = Index;
- string val = null;
- int len = Encdec.Dec_uint32le(Buf, i);
- i += 12;
- if (len != 0)
- {
- len--;
- int size = len * 2;
- try
- {
- if (size < 0 || size > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE");
- i += size + 2;
- }
- catch (UnsupportedEncodingException)
- {
- }
- }
- Advance(i - Index);
- return val;
- }
-
- private int GetDceReferent(object obj)
- {
- Entry e;
- if (Referents == null)
- {
- Referents = new Hashtable();
- Referent = 1;
- }
- if ((e = (Entry)Referents.Get(obj)) == null)
- {
- e = new Entry();
- e.Referent = Referent++;
- e.Obj = obj;
- Referents.Put(obj, e);
- }
- return e.Referent;
- }
-
- public virtual void Enc_ndr_referent(object obj, int type)
- {
- if (obj == null)
- {
- Enc_ndr_long(0);
- return;
- }
- switch (type)
- {
- case 1:
- case 3:
- {
- Enc_ndr_long(Runtime.IdentityHashCode(obj));
- return;
- }
-
- case 2:
- {
- Enc_ndr_long(GetDceReferent(obj));
- return;
- }
- }
- }
-
- public override string ToString()
- {
- return "start=" + Start + ",index=" + Index + ",length=" + GetLength();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs
deleted file mode 100644
index 7757735f8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-
-namespace SharpCifs.Dcerpc.Ndr
-{
-
- public class NdrException : IOException
- {
- public static readonly string NoNullRef = "ref pointer cannot be null";
-
- public static readonly string InvalidConformance = "invalid array conformance";
-
- public NdrException(string msg) : base(msg)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs
deleted file mode 100644
index 9e2932337..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Ndr
-{
- public class NdrHyper : NdrObject
- {
- public long Value;
-
- public NdrHyper(long value)
- {
- this.Value = value;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Enc_ndr_hyper(Value);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- Value = src.Dec_ndr_hyper();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs
deleted file mode 100644
index 74d90465e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Ndr
-{
- public class NdrLong : NdrObject
- {
- public int Value;
-
- public NdrLong(int value)
- {
- this.Value = value;
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Enc_ndr_long(Value);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- Value = src.Dec_ndr_long();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs
deleted file mode 100644
index 8951fa202..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Ndr
-{
- public abstract class NdrObject
- {
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public abstract void Encode(NdrBuffer dst);
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public abstract void Decode(NdrBuffer src);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs
deleted file mode 100644
index e2ea8c65b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Ndr
-{
- public class NdrShort : NdrObject
- {
- public int Value;
-
- public NdrShort(int value)
- {
- this.Value = value & unchecked(0xFF);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Enc_ndr_short(Value);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- Value = src.Dec_ndr_short();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs
deleted file mode 100644
index 8309dea66..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc.Ndr
-{
- public class NdrSmall : NdrObject
- {
- public int Value;
-
- public NdrSmall(int value)
- {
- this.Value = value & unchecked(0xFF);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Enc_ndr_small(Value);
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- Value = src.Dec_ndr_small();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs
deleted file mode 100644
index aa33d3522..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs
+++ /dev/null
@@ -1,285 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Dcerpc.Ndr;
-
-namespace SharpCifs.Dcerpc
-{
- public class Rpc
- {
- public class UuidT : NdrObject
- {
- public int TimeLow;
-
- public short TimeMid;
-
- public short TimeHiAndVersion;
-
- public byte ClockSeqHiAndReserved;
-
- public byte ClockSeqLow;
-
- public byte[] Node;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(TimeLow);
- dst.Enc_ndr_short(TimeMid);
- dst.Enc_ndr_short(TimeHiAndVersion);
- dst.Enc_ndr_small(ClockSeqHiAndReserved);
- dst.Enc_ndr_small(ClockSeqLow);
- int nodes = 6;
- int nodei = dst.Index;
- dst.Advance(1 * nodes);
- dst = dst.Derive(nodei);
- for (int i = 0; i < nodes; i++)
- {
- dst.Enc_ndr_small(Node[i]);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- TimeLow = src.Dec_ndr_long();
- TimeMid = (short)src.Dec_ndr_short();
- TimeHiAndVersion = (short)src.Dec_ndr_short();
- ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
- ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
- int nodes = 6;
- int nodei = src.Index;
- src.Advance(1 * nodes);
- if (Node == null)
- {
- if (nodes < 0 || nodes > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Node = new byte[nodes];
- }
- src = src.Derive(nodei);
- for (int i = 0; i < nodes; i++)
- {
- Node[i] = unchecked((byte)src.Dec_ndr_small());
- }
- }
- }
-
- public class PolicyHandle : NdrObject
- {
- public int Type;
-
- public UuidT Uuid;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_long(Type);
- dst.Enc_ndr_long(Uuid.TimeLow);
- dst.Enc_ndr_short(Uuid.TimeMid);
- dst.Enc_ndr_short(Uuid.TimeHiAndVersion);
- dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved);
- dst.Enc_ndr_small(Uuid.ClockSeqLow);
- int uuidNodes = 6;
- int uuidNodei = dst.Index;
- dst.Advance(1 * uuidNodes);
- dst = dst.Derive(uuidNodei);
- for (int i = 0; i < uuidNodes; i++)
- {
- dst.Enc_ndr_small(Uuid.Node[i]);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Type = src.Dec_ndr_long();
- src.Align(4);
- if (Uuid == null)
- {
- Uuid = new UuidT();
- }
- Uuid.TimeLow = src.Dec_ndr_long();
- Uuid.TimeMid = (short)src.Dec_ndr_short();
- Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
- Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
- Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
- int uuidNodes = 6;
- int uuidNodei = src.Index;
- src.Advance(1 * uuidNodes);
- if (Uuid.Node == null)
- {
- if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Uuid.Node = new byte[uuidNodes];
- }
- src = src.Derive(uuidNodei);
- for (int i = 0; i < uuidNodes; i++)
- {
- Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small());
- }
- }
- }
-
- public class Unicode_string : NdrObject
- {
- public short Length;
-
- public short MaximumLength;
-
- public short[] Buffer;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- dst.Enc_ndr_short(Length);
- dst.Enc_ndr_short(MaximumLength);
- dst.Enc_ndr_referent(Buffer, 1);
- if (Buffer != null)
- {
- dst = dst.Deferred;
- int bufferl = Length / 2;
- int buffers = MaximumLength / 2;
- dst.Enc_ndr_long(buffers);
- dst.Enc_ndr_long(0);
- dst.Enc_ndr_long(bufferl);
- int bufferi = dst.Index;
- dst.Advance(2 * bufferl);
- dst = dst.Derive(bufferi);
- for (int i = 0; i < bufferl; i++)
- {
- dst.Enc_ndr_short(Buffer[i]);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- Length = (short)src.Dec_ndr_short();
- MaximumLength = (short)src.Dec_ndr_short();
- int bufferp = src.Dec_ndr_long();
- if (bufferp != 0)
- {
- src = src.Deferred;
- int buffers = src.Dec_ndr_long();
- src.Dec_ndr_long();
- int bufferl = src.Dec_ndr_long();
- int bufferi = src.Index;
- src.Advance(2 * bufferl);
- if (Buffer == null)
- {
- if (buffers < 0 || buffers > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- Buffer = new short[buffers];
- }
- src = src.Derive(bufferi);
- for (int i = 0; i < bufferl; i++)
- {
- Buffer[i] = (short)src.Dec_ndr_short();
- }
- }
- }
- }
-
- public class SidT : NdrObject
- {
- public byte Revision;
-
- public byte SubAuthorityCount;
-
- public byte[] IdentifierAuthority;
-
- public int[] SubAuthority;
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Encode(NdrBuffer dst)
- {
- dst.Align(4);
- int subAuthoritys = SubAuthorityCount;
- dst.Enc_ndr_long(subAuthoritys);
- dst.Enc_ndr_small(Revision);
- dst.Enc_ndr_small(SubAuthorityCount);
- int identifierAuthoritys = 6;
- int identifierAuthorityi = dst.Index;
- dst.Advance(1 * identifierAuthoritys);
- int subAuthorityi = dst.Index;
- dst.Advance(4 * subAuthoritys);
- dst = dst.Derive(identifierAuthorityi);
- for (int i = 0; i < identifierAuthoritys; i++)
- {
- dst.Enc_ndr_small(IdentifierAuthority[i]);
- }
- dst = dst.Derive(subAuthorityi);
- for (int i1 = 0; i1 < subAuthoritys; i1++)
- {
- dst.Enc_ndr_long(SubAuthority[i1]);
- }
- }
-
- /// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
- public override void Decode(NdrBuffer src)
- {
- src.Align(4);
- int subAuthoritys = src.Dec_ndr_long();
- Revision = unchecked((byte)src.Dec_ndr_small());
- SubAuthorityCount = unchecked((byte)src.Dec_ndr_small());
- int identifierAuthoritys = 6;
- int identifierAuthorityi = src.Index;
- src.Advance(1 * identifierAuthoritys);
- int subAuthorityi = src.Index;
- src.Advance(4 * subAuthoritys);
- if (IdentifierAuthority == null)
- {
- if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- IdentifierAuthority = new byte[identifierAuthoritys];
- }
- src = src.Derive(identifierAuthorityi);
- for (int i = 0; i < identifierAuthoritys; i++)
- {
- IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small());
- }
- if (SubAuthority == null)
- {
- if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF))
- {
- throw new NdrException(NdrException.InvalidConformance);
- }
- SubAuthority = new int[subAuthoritys];
- }
- src = src.Derive(subAuthorityi);
- for (int i1 = 0; i1 < subAuthoritys; i1++)
- {
- SubAuthority[i1] = src.Dec_ndr_long();
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs
deleted file mode 100644
index bef4be214..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Dcerpc
-{
- public class Uuid : Rpc.UuidT
- {
- public static int Hex_to_bin(char[] arr, int offset, int length)
- {
- int value = 0;
- int ai;
- int count;
- count = 0;
- for (ai = offset; ai < arr.Length && count < length; ai++)
- {
- value <<= 4;
- switch (arr[ai])
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- {
- value += arr[ai] - '0';
- break;
- }
-
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- {
- value += 10 + (arr[ai] - 'A');
- break;
- }
-
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- {
- value += 10 + (arr[ai] - 'a');
- break;
- }
-
- default:
- {
- throw new ArgumentException(new string(arr, offset, length));
- }
- }
- count++;
- }
- return value;
- }
-
- internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4',
- '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
-
- public static string Bin_to_hex(int value, int length)
- {
- char[] arr = new char[length];
- int ai = arr.Length;
- while (ai-- > 0)
- {
- arr[ai] = Hexchars[value & unchecked(0xF)];
- value = (int)(((uint)value) >> 4);
- }
- return new string(arr);
- }
-
- private static byte B(int i)
- {
- return unchecked((byte)(i & unchecked(0xFF)));
- }
-
- private static short S(int i)
- {
- return (short)(i & unchecked(0xFFFF));
- }
-
- public Uuid(Rpc.UuidT uuid)
- {
- TimeLow = uuid.TimeLow;
- TimeMid = uuid.TimeMid;
- TimeHiAndVersion = uuid.TimeHiAndVersion;
- ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved;
- ClockSeqLow = uuid.ClockSeqLow;
- Node = new byte[6];
- Node[0] = uuid.Node[0];
- Node[1] = uuid.Node[1];
- Node[2] = uuid.Node[2];
- Node[3] = uuid.Node[3];
- Node[4] = uuid.Node[4];
- Node[5] = uuid.Node[5];
- }
-
- public Uuid(string str)
- {
- char[] arr = str.ToCharArray();
- TimeLow = Hex_to_bin(arr, 0, 8);
- TimeMid = S(Hex_to_bin(arr, 9, 4));
- TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4));
- ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2));
- ClockSeqLow = B(Hex_to_bin(arr, 21, 2));
- Node = new byte[6];
- Node[0] = B(Hex_to_bin(arr, 24, 2));
- Node[1] = B(Hex_to_bin(arr, 26, 2));
- Node[2] = B(Hex_to_bin(arr, 28, 2));
- Node[3] = B(Hex_to_bin(arr, 30, 2));
- Node[4] = B(Hex_to_bin(arr, 32, 2));
- Node[5] = B(Hex_to_bin(arr, 34, 2));
- }
-
- public override string ToString()
- {
- return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex
- (TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex
- (ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex
- (Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node
- [5], 2);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs
deleted file mode 100644
index b0c36898c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Dcerpc
-{
- public class UnicodeString : Rpc.Unicode_string
- {
- internal bool Zterm;
-
- public UnicodeString(bool zterm)
- {
- this.Zterm = zterm;
- }
-
- public UnicodeString(Rpc.Unicode_string rus, bool zterm)
- {
- Length = rus.Length;
- MaximumLength = rus.MaximumLength;
- Buffer = rus.Buffer;
- this.Zterm = zterm;
- }
-
- public UnicodeString(string str, bool zterm)
- {
- this.Zterm = zterm;
- int len = str.Length;
- int zt = zterm ? 1 : 0;
- Length = MaximumLength = (short)((len + zt) * 2);
- Buffer = new short[len + zt];
- int i;
- for (i = 0; i < len; i++)
- {
- Buffer[i] = (short)str[i];
- }
- if (zterm)
- {
- Buffer[i] = 0;
- }
- }
-
- public override string ToString()
- {
- int len = Length / 2 - (Zterm ? 1 : 0);
- char[] ca = new char[len];
- for (int i = 0; i < len; i++)
- {
- ca[i] = (char)Buffer[i];
- }
- return new string(ca, 0, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs
deleted file mode 100644
index c94d0a260..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Smb;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- public class Lmhosts
- {
- private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"
- );
-
- private static readonly Hashtable Tab = new Hashtable();
-
- private static long _lastModified = 1L;
-
- private static int _alt;
-
- private static LogStream _log = LogStream.GetInstance();
-
- /// <summary>
- /// This is really just for
- /// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
- /// . It does
- /// not throw an
- /// <see cref="UnknownHostException">Sharpen.UnknownHostException</see>
- /// because this
- /// is queried frequently and exceptions would be rather costly to
- /// throw on a regular basis here.
- /// </summary>
- public static NbtAddress GetByName(string host)
- {
- lock (typeof(Lmhosts))
- {
- return GetByName(new Name(host, 0x20, null));
- }
- }
-
- internal static NbtAddress GetByName(Name name)
- {
- lock (typeof(Lmhosts))
- {
- NbtAddress result = null;
- try
- {
- if (Filename != null)
- {
- FilePath f = new FilePath(Filename);
- long lm;
- if ((lm = f.LastModified()) > _lastModified)
- {
- _lastModified = lm;
- Tab.Clear();
- _alt = 0;
-
- //path -> fileStream
- //Populate(new FileReader(f));
- Populate(new FileReader(new FileStream(f, FileMode.Open)));
- }
- result = (NbtAddress)Tab[name];
- }
- }
- catch (FileNotFoundException fnfe)
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("lmhosts file: " + Filename);
- Runtime.PrintStackTrace(fnfe, _log);
- }
- }
- catch (IOException ioe)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- }
- return result;
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static void Populate(StreamReader r)
- {
- string line;
- BufferedReader br = new BufferedReader((InputStreamReader)r);
- while ((line = br.ReadLine()) != null)
- {
- line = line.ToUpper().Trim();
- if (line.Length == 0)
- {
- }
- else
- {
- if (line[0] == '#')
- {
- if (line.StartsWith("#INCLUDE "))
- {
- line = Runtime.Substring(line, line.IndexOf('\\'));
- string url = "smb:" + line.Replace('\\', '/');
- if (_alt > 0)
- {
- try
- {
- Populate(new InputStreamReader(new SmbFileInputStream(url)));
- }
- catch (IOException ioe)
- {
- _log.WriteLine("lmhosts URL: " + url);
- Runtime.PrintStackTrace(ioe, _log);
- continue;
- }
- _alt--;
- while ((line = br.ReadLine()) != null)
- {
- line = line.ToUpper().Trim();
- if (line.StartsWith("#END_ALTERNATE"))
- {
- break;
- }
- }
- }
- else
- {
- Populate(new InputStreamReader(new SmbFileInputStream(url)));
- }
- }
- else
- {
- if (line.StartsWith("#BEGIN_ALTERNATE"))
- {
- _alt++;
- }
- else
- {
- if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
- {
- _alt--;
- throw new IOException("no lmhosts alternate includes loaded");
- }
- }
- }
- }
- else
- {
- if (char.IsDigit(line[0]))
- {
- char[] data = line.ToCharArray();
- int ip;
- int i;
- int j;
- Name name;
- NbtAddress addr;
- char c;
- c = '.';
- ip = i = 0;
- for (; i < data.Length && c == '.'; i++)
- {
- int b = unchecked(0x00);
- for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
- {
- b = b * 10 + c - '0';
- }
- ip = (ip << 8) + b;
- }
- while (i < data.Length && char.IsWhiteSpace(data[i]))
- {
- i++;
- }
- j = i;
- while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
- {
- j++;
- }
- name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
- );
- addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
- , NbtAddress.UnknownMacAddress);
- Tab.Put(name, addr);
- }
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs
deleted file mode 100644
index 6c37d57a4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs
+++ /dev/null
@@ -1,269 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Text;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- public class Name
- {
- private const int TypeOffset = 31;
-
- private const int ScopeOffset = 33;
-
- private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope"
- );
-
- internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding"
- , Runtime.GetProperty("file.encoding"));
-
- public string name;
-
- public string Scope;
-
- public int HexCode;
-
- internal int SrcHashCode;
-
- public Name()
- {
- }
-
- public Name(string name, int hexCode, string scope)
- {
- if (name.Length > 15)
- {
- name = Runtime.Substring(name, 0, 15);
- }
- this.name = name.ToUpper();
- this.HexCode = hexCode;
- this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope;
- SrcHashCode = 0;
- }
-
- internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
- {
- // write 0x20 in first byte
- dst[dstIndex] = unchecked(0x20);
- // write name
- try
- {
- byte[] tmp = Runtime.GetBytesForString(name, OemEncoding
- );
- int i;
- for (i = 0; i < tmp.Length; i++)
- {
- dst[dstIndex + (2 * i + 1)] = unchecked((byte)(((tmp[i] & unchecked(0xF0))
- >> 4) + unchecked(0x41)));
- dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F))
- + unchecked(0x41)));
- }
- for (; i < 15; i++)
- {
- dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43));
- dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41));
- }
- dst[dstIndex + TypeOffset] = unchecked((byte)(((HexCode & unchecked(0xF0)
- ) >> 4) + unchecked(0x41)));
- dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
- }
- catch (UnsupportedEncodingException)
- {
- }
- return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset);
- }
-
- internal virtual int ReadWireFormat(byte[] src, int srcIndex)
- {
- byte[] tmp = new byte[ScopeOffset];
- int length = 15;
- for (int i = 0; i < 15; i++)
- {
- tmp[i] = unchecked((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF))
- - unchecked(0x41)) << 4));
- tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF)
- ) - unchecked(0x41)) & unchecked(0x0F)));
- if (tmp[i] != unchecked((byte)' '))
- {
- length = i + 1;
- }
- }
- try
- {
- name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding
- );
- }
- catch (UnsupportedEncodingException)
- {
- }
- HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
- HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(
- 0x41)) & unchecked(0x0F);
- return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
- }
-
- internal int ReadWireFormatDos(byte[] src, int srcIndex)
- {
-
- int length = 15;
- byte[] tmp = new byte[length];
-
- Array.Copy(src, srcIndex, tmp, 0, length);
-
- try
- {
- name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
- }
- catch (Exception ex)
- {
-
- }
-
- HexCode = src[srcIndex + length];
-
- return length + 1;
- }
-
-
- internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex)
- {
- if (Scope == null)
- {
- dst[dstIndex] = unchecked(unchecked(0x00));
- return 1;
- }
- // copy new scope in
- dst[dstIndex++] = unchecked((byte)('.'));
- try
- {
- Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding
- ), 0, dst, dstIndex, Scope.Length);
- }
- catch (UnsupportedEncodingException)
- {
- }
- dstIndex += Scope.Length;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // now go over scope backwards converting '.' to label length
- int i = dstIndex - 2;
- int e = i - Scope.Length;
- int c = 0;
- do
- {
- if (dst[i] == '.')
- {
- dst[i] = unchecked((byte)c);
- c = 0;
- }
- else
- {
- c++;
- }
- }
- while (i-- > e);
- return Scope.Length + 2;
- }
-
- internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- int n;
- StringBuilder sb;
- if ((n = src[srcIndex++] & unchecked(0xFF)) == 0)
- {
- Scope = null;
- return 1;
- }
- try
- {
- sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
- srcIndex += n;
- while ((n = src[srcIndex++] & unchecked(0xFF)) != 0)
- {
- sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
- srcIndex += n;
- }
- Scope = sb.ToString();
- }
- catch (UnsupportedEncodingException)
- {
- }
- return srcIndex - start;
- }
-
- public override int GetHashCode()
- {
- int result;
- result = name.GetHashCode();
- result += 65599 * HexCode;
- result += 65599 * SrcHashCode;
- if (Scope != null && Scope.Length != 0)
- {
- result += Scope.GetHashCode();
- }
- return result;
- }
-
- public override bool Equals(object obj)
- {
- Name n;
- if (!(obj is Name))
- {
- return false;
- }
- n = (Name)obj;
- if (Scope == null && n.Scope == null)
- {
- return name.Equals(n.name) && HexCode == n.HexCode;
- }
- return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope);
- }
-
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
-
- //return "";
-
- string n = name;
- // fix MSBROWSE name
- if (n == null)
- {
- n = "null";
- }
- else
- {
- if (n[0] == unchecked(0x01))
- {
- char[] c = n.ToCharArray();
- c[0] = '.';
- c[1] = '.';
- c[14] = '.';
- n = new string(c);
- }
- }
- sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">");
- if (Scope != null)
- {
- sb.Append(".").Append(Scope);
- }
- return sb.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs
deleted file mode 100644
index 646e65bf8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Netbios
-{
- internal class NameQueryRequest : NameServicePacket
- {
- internal NameQueryRequest(Name name)
- {
- QuestionName = name;
- QuestionType = Nb;
- }
-
- internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
- {
- return WriteQuestionSectionWireFormat(dst, dstIndex);
- }
-
- internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
- {
- return ReadQuestionSectionWireFormat(src, srcIndex);
- }
-
- internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "NameQueryRequest[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs
deleted file mode 100644
index c7fac8e93..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Netbios
-{
- internal class NameQueryResponse : NameServicePacket
- {
- public NameQueryResponse()
- {
- RecordName = new Name();
- }
-
- internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
- {
- return ReadResourceRecordWireFormat(src, srcIndex);
- }
-
- internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
- {
- if (ResultCode != 0 || OpCode != Query)
- {
- return 0;
- }
- bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
- int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5;
- srcIndex += 2;
- int address = ReadInt4(src, srcIndex);
- if (address != 0)
- {
- AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType);
- }
- else
- {
- AddrEntry[AddrIndex] = null;
- }
- return 6;
- }
-
- public override string ToString()
- {
- return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry
- + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs
deleted file mode 100644
index 01700e64a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs
+++ /dev/null
@@ -1,660 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Linq;
-using System.Threading;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-using Thread = SharpCifs.Util.Sharpen.Thread;
-
-namespace SharpCifs.Netbios
-{
- internal class NameServiceClient : IRunnable
- {
- internal const int DefaultSoTimeout = 5000;
-
- internal const int DefaultRcvBufSize = 576;
-
- internal const int DefaultSndBufSize = 576;
-
- internal const int NameServiceUdpPort = 137;
-
- internal const int DefaultRetryCount = 2;
-
- internal const int DefaultRetryTimeout = 3000;
-
- internal const int ResolverLmhosts = 1;
-
- internal const int ResolverBcast = 2;
-
- internal const int ResolverWins = 3;
-
- private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size"
- , DefaultSndBufSize);
-
- private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size"
- , DefaultRcvBufSize);
-
- private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout",
- DefaultSoTimeout);
-
- private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount"
- , DefaultRetryCount);
-
- private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout"
- , DefaultRetryTimeout);
-
- private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137);
-
- private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr"
- , null);
-
- private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder");
-
- private static LogStream _log = LogStream.GetInstance();
-
- private readonly object _lock = new object();
-
- private int _lport;
-
- private int _closeTimeout;
-
- private byte[] _sndBuf;
-
- private byte[] _rcvBuf;
-
- private SocketEx _socket;
-
- private Hashtable _responseTable = new Hashtable();
-
- private Thread _thread;
-
- private int _nextNameTrnId;
-
- private int[] _resolveOrder;
-
- private bool _waitResponse = true;
-
- private AutoResetEvent _autoResetWaitReceive;
-
- internal IPAddress laddr;
-
- internal IPAddress Baddr;
-
- public NameServiceClient()
- : this(Lport, Laddr)
- {
- }
-
- internal NameServiceClient(int lport, IPAddress laddr)
- {
- this._lport = lport;
-
- this.laddr = laddr
- ?? Config.GetLocalHost()
- ?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();
-
- try
- {
- Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
- }
- catch (Exception ex)
- {
- }
-
- _sndBuf = new byte[SndBufSize];
- _rcvBuf = new byte[RcvBufSize];
-
-
- if (string.IsNullOrEmpty(Ro))
- {
- if (NbtAddress.GetWinsAddress() == null)
- {
- _resolveOrder = new int[2];
- _resolveOrder[0] = ResolverLmhosts;
- _resolveOrder[1] = ResolverBcast;
- }
- else
- {
- _resolveOrder = new int[3];
- _resolveOrder[0] = ResolverLmhosts;
- _resolveOrder[1] = ResolverWins;
- _resolveOrder[2] = ResolverBcast;
- }
- }
- else
- {
- int[] tmp = new int[3];
- StringTokenizer st = new StringTokenizer(Ro, ",");
- int i = 0;
- while (st.HasMoreTokens())
- {
- string s = st.NextToken().Trim();
- if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
- {
- tmp[i++] = ResolverLmhosts;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "WINS"))
- {
- if (NbtAddress.GetWinsAddress() == null)
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
- );
- }
- continue;
- }
- tmp[i++] = ResolverWins;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "BCAST"))
- {
- tmp[i++] = ResolverBcast;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "DNS"))
- {
- }
- else
- {
- // skip
- if (_log.Level > 1)
- {
- _log.WriteLine("unknown resolver method: " + s);
- }
- }
- }
- }
- }
- }
- _resolveOrder = new int[i];
- Array.Copy(tmp, 0, _resolveOrder, 0, i);
- }
- }
-
- internal virtual int GetNextNameTrnId()
- {
- if ((++_nextNameTrnId & unchecked(0xFFFF)) == 0)
- {
- _nextNameTrnId = 1;
- }
- return _nextNameTrnId;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual void EnsureOpen(int timeout)
- {
- _closeTimeout = 0;
- if (SoTimeout != 0)
- {
- _closeTimeout = Math.Max(SoTimeout, timeout);
- }
- // If socket is still good, the new closeTimeout will
- // be ignored; see tryClose comment.
- if (_socket == null)
- {
- _socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
-
- //IPAddress.`Address` property deleted
- //_socket.Bind(new IPEndPoint(laddr.Address, _lport));
- _socket.Bind(new IPEndPoint(laddr, _lport));
-
- if (_waitResponse)
- {
- _thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
- _thread.SetDaemon(true);
- _thread.Start();
- }
- }
- }
-
- internal virtual void TryClose()
- {
- lock (_lock)
- {
- if (_socket != null)
- {
- //Socket.`Close` method deleted
- //_socket.Close();
- _socket.Dispose();
- _socket = null;
- }
- _thread = null;
-
- if (_waitResponse)
- {
- _responseTable.Clear();
- } else
- {
- _autoResetWaitReceive.Set();
- }
- }
- }
-
- public virtual void Run()
- {
- int nameTrnId;
- NameServicePacket response;
-
- try
- {
-
- while (_thread == Thread.CurrentThread())
- {
- _socket.SoTimeOut = _closeTimeout;
-
- int len = _socket.Receive(_rcvBuf, 0, RcvBufSize);
-
- if (_log.Level > 3)
- {
- _log.WriteLine("NetBIOS: new data read from socket");
- }
- nameTrnId = NameServicePacket.ReadNameTrnId(_rcvBuf, 0);
- response = (NameServicePacket)_responseTable.Get(nameTrnId);
-
-
- if (response == null || response.Received)
- {
- continue;
- }
-
- lock (response)
- {
- response.ReadWireFormat(_rcvBuf, 0);
-
- if (_log.Level > 3)
- {
- _log.WriteLine(response);
- Hexdump.ToHexdump(_log, _rcvBuf, 0, len);
- }
-
- if (response.IsResponse)
- {
- response.Received = true;
-
- Runtime.Notify(response);
- }
- }
- }
-
- }
- catch (TimeoutException) { }
- catch (Exception ex)
- {
- if (_log.Level > 2)
- {
- Runtime.PrintStackTrace(ex, _log);
- }
- }
- finally
- {
- TryClose();
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual void Send(NameServicePacket request, NameServicePacket response,
- int timeout)
- {
- int nid = 0;
- int max = NbtAddress.Nbns.Length;
- if (max == 0)
- {
- max = 1;
- }
-
- lock (response)
- {
-
- while (max-- > 0)
- {
- try
- {
- lock (_lock)
- {
- request.NameTrnId = GetNextNameTrnId();
- nid = request.NameTrnId;
- response.Received = false;
- _responseTable.Put(nid, response);
- EnsureOpen(timeout + 1000);
- int requestLenght = request.WriteWireFormat(_sndBuf, 0);
- _socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
- if (_log.Level > 3)
- {
- _log.WriteLine(request);
- Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
- }
-
- }
- if (_waitResponse)
- {
- long start = Runtime.CurrentTimeMillis();
- while (timeout > 0)
- {
- Runtime.Wait(response, timeout);
- if (response.Received && request.QuestionType == response.RecordType)
- {
- return;
- }
- response.Received = false;
- timeout -= (int)(Runtime.CurrentTimeMillis() - start);
- }
- }
- }
- catch (Exception ie)
- {
- throw new IOException(ie.Message);
- }
- finally
- {
- //Sharpen.Collections.Remove(responseTable, nid);
- if (_waitResponse)
- {
- _responseTable.Remove(nid);
- }
- }
- if (_waitResponse)
- {
- lock (_lock)
- {
- if (NbtAddress.IsWins(request.Addr) == false)
- {
- break;
- }
- if (request.Addr == NbtAddress.GetWinsAddress())
- {
- NbtAddress.SwitchWins();
- }
- request.Addr = NbtAddress.GetWinsAddress();
- }
- }
- }
- }
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
- {
- int n;
- NameQueryRequest request = new NameQueryRequest(name);
- NameQueryResponse response = new NameQueryResponse();
- request.Addr = addr ?? NbtAddress.GetWinsAddress();
- request.IsBroadcast = request.Addr == null;
- if (request.IsBroadcast)
- {
- request.Addr = Baddr;
- n = RetryCount;
- }
- else
- {
- request.IsBroadcast = false;
- n = 1;
- }
- do
- {
- try
- {
- Send(request, response, RetryTimeout);
- }
- catch (IOException ioe)
- {
- if (_log.Level > 1)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- throw new UnknownHostException(ioe);
- }
- if (response.Received && response.ResultCode == 0)
- {
- return response.AddrEntry;
- }
- }
- while (--n > 0 && request.IsBroadcast);
- throw new UnknownHostException();
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual NbtAddress GetByName(Name name, IPAddress addr)
- {
- int n;
-
- NameQueryRequest request = new NameQueryRequest(name);
- NameQueryResponse response = new NameQueryResponse();
- if (addr != null)
- {
- request.Addr = addr;
- request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked(unchecked(0xFF)));
- n = RetryCount;
- do
- {
- try
- {
- Send(request, response, RetryTimeout);
- }
- catch (IOException ioe)
- {
- if (_log.Level > 1)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- throw new UnknownHostException(ioe);
- }
- if (response.Received && response.ResultCode == 0
- && response.IsResponse)
- {
- int last = response.AddrEntry.Length - 1;
- response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode();
- return response.AddrEntry[last];
- }
- }
- while (--n > 0 && request.IsBroadcast);
- throw new UnknownHostException();
- }
- for (int i = 0; i < _resolveOrder.Length; i++)
- {
- try
- {
- switch (_resolveOrder[i])
- {
- case ResolverLmhosts:
- {
- NbtAddress ans = Lmhosts.GetByName(name);
- if (ans != null)
- {
- ans.HostName.SrcHashCode = 0;
- // just has to be different
- // from other methods
- return ans;
- }
- break;
- }
-
- case ResolverWins:
- case ResolverBcast:
- {
- if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName
- && name.HexCode != unchecked(0x1d))
- {
- request.Addr = NbtAddress.GetWinsAddress();
- request.IsBroadcast = false;
- }
- else
- {
- request.Addr = Baddr;
- request.IsBroadcast = true;
- }
- n = RetryCount;
- while (n-- > 0)
- {
- try
- {
- Send(request, response, RetryTimeout);
- }
- catch (IOException ioe)
- {
- if (_log.Level > 1)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- throw new UnknownHostException(ioe);
- }
- if (response.Received && response.ResultCode == 0
- && response.IsResponse)
- {
-
- response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
- return response.AddrEntry[0];
- }
- if (_resolveOrder[i] == ResolverWins)
- {
- break;
- }
- }
- break;
- }
- }
- }
- catch (IOException)
- {
- }
- }
- throw new UnknownHostException();
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
- {
- int n;
- int srcHashCode;
- NodeStatusRequest request;
- NodeStatusResponse response;
- response = new NodeStatusResponse(addr);
- request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
- request.Addr = addr.GetInetAddress();
- n = RetryCount;
- while (n-- > 0)
- {
- try
- {
- Send(request, response, RetryTimeout);
- }
- catch (IOException ioe)
- {
- if (_log.Level > 1)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- throw new UnknownHostException(ioe);
- }
- if (response.Received && response.ResultCode == 0)
- {
- srcHashCode = request.Addr.GetHashCode();
- for (int i = 0; i < response.AddressArray.Length; i++)
- {
- response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
- }
- return response.AddressArray;
- }
- }
- throw new UnknownHostException();
- }
-
- internal virtual NbtAddress[] GetHosts()
- {
- try
- {
- _waitResponse = false;
-
- byte[] bAddrBytes = laddr.GetAddressBytes();
-
- for (int i = 1; i <= 254; i++)
- {
- NodeStatusRequest request;
- NodeStatusResponse response;
-
- byte[] addrBytes = {
- bAddrBytes[0],
- bAddrBytes[1],
- bAddrBytes[2],
- (byte)i
- };
-
- IPAddress addr = new IPAddress(addrBytes);
-
- //response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
- // (int)addr.Address, false, 0x20));
- response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
- BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20));
-
- request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x20), null));
- request.Addr = addr;
- Send(request, response, 0);
- }
-
- }
- catch (IOException ioe)
- {
- if (_log.Level > 1)
- {
- Runtime.PrintStackTrace(ioe, _log);
- }
- throw new UnknownHostException(ioe);
- }
-
- _autoResetWaitReceive = new AutoResetEvent(false);
- _thread = new Thread(this);
- _thread.SetDaemon(true);
- _thread.Start();
-
- _autoResetWaitReceive.WaitOne();
-
- List<NbtAddress> result = new List<NbtAddress>();
-
- foreach (var key in _responseTable.Keys)
- {
- NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key];
-
- if (resp.Received && resp.ResultCode == 0)
- {
- foreach (var entry in resp.AddressArray)
- {
- if (entry.HostName.HexCode == 0x20)
- {
- result.Add(entry);
- }
- }
- }
- }
-
- _responseTable.Clear();
-
- _waitResponse = true;
-
- return result.Count > 0 ? result.ToArray() : null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs
deleted file mode 100644
index 28e98406e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs
+++ /dev/null
@@ -1,448 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.Net;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- internal abstract class NameServicePacket
- {
- internal const int Query = 0;
-
- internal const int Wack = 7;
-
- internal const int FmtErr = 0x1;
-
- internal const int SrvErr = 0x2;
-
- internal const int ImpErr = 0x4;
-
- internal const int RfsErr = 0x5;
-
- internal const int ActErr = 0x6;
-
- internal const int CftErr = 0x7;
-
- internal const int NbIn = 0x00200001;
-
- internal const int NbstatIn = 0x00210001;
-
- internal const int Nb = 0x0020;
-
- internal const int Nbstat = 0x0021;
-
- internal const int In = 0x0001;
-
- internal const int A = 0x0001;
-
- internal const int Ns = 0x0002;
-
- internal const int Null = 0x000a;
-
- internal const int HeaderLength = 12;
-
- internal const int OpcodeOffset = 2;
-
- internal const int QuestionOffset = 4;
-
- internal const int AnswerOffset = 6;
-
- internal const int AuthorityOffset = 8;
-
- internal const int AdditionalOffset = 10;
-
- // opcode
- // rcode
- // type/class
- // header field offsets
- internal static void WriteInt2(int val, byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
- dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
- }
-
- internal static void WriteInt4(int val, byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
- dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
- }
-
- internal static int ReadInt2(byte[] src, int srcIndex)
- {
- return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
- 0xFF));
- }
-
- internal static int ReadInt4(byte[] src, int srcIndex)
- {
- return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
- 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
- [srcIndex + 3] & unchecked(0xFF));
- }
-
- internal static int ReadNameTrnId(byte[] src, int srcIndex)
- {
- return ReadInt2(src, srcIndex);
- }
-
- internal int AddrIndex;
-
- internal NbtAddress[] AddrEntry;
-
- internal int NameTrnId;
-
- internal int OpCode;
-
- internal int ResultCode;
-
- internal int QuestionCount;
-
- internal int AnswerCount;
-
- internal int AuthorityCount;
-
- internal int AdditionalCount;
-
- internal bool Received;
-
- internal bool IsResponse;
-
- internal bool IsAuthAnswer;
-
- internal bool IsTruncated;
-
- internal bool IsRecurDesired;
-
- internal bool IsRecurAvailable;
-
- internal bool IsBroadcast;
-
- internal Name QuestionName;
-
- internal Name RecordName;
-
- internal int QuestionType;
-
- internal int QuestionClass;
-
- internal int RecordType;
-
- internal int RecordClass;
-
- internal int Ttl;
-
- internal int RDataLength;
-
- internal IPAddress Addr;
-
- public NameServicePacket()
- {
- IsRecurDesired = true;
- IsBroadcast = true;
- QuestionCount = 1;
- QuestionClass = In;
- }
-
- internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dstIndex += WriteHeaderWireFormat(dst, dstIndex);
- dstIndex += WriteBodyWireFormat(dst, dstIndex);
- return dstIndex - start;
- }
-
- internal virtual int ReadWireFormat(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- srcIndex += ReadHeaderWireFormat(src, srcIndex);
- srcIndex += ReadBodyWireFormat(src, srcIndex);
- return srcIndex - start;
- }
-
- internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(NameTrnId, dst, dstIndex);
- dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer
- ? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01)
- : unchecked(0x00))));
- dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked(
- 0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) :
- unchecked(0x00)) + (ResultCode & unchecked(0x0F))));
- WriteInt2(QuestionCount, dst, start + QuestionOffset);
- WriteInt2(AnswerCount, dst, start + AnswerOffset);
- WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
- WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
- return HeaderLength;
- }
-
- internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
- {
- NameTrnId = ReadInt2(src, srcIndex);
- IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false
- : true;
- OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3;
- IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ?
- false : true;
- IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false
- : true;
- IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ?
- false : true;
- IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80))
- == 0) ? false : true;
- IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0)
- ? false : true;
- ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
- QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
- AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
- AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
- AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
- return HeaderLength;
- }
-
- internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
- WriteInt2(QuestionType, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(QuestionClass, dst, dstIndex);
- dstIndex += 2;
- return dstIndex - start;
- }
-
- internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
- QuestionType = ReadInt2(src, srcIndex);
- srcIndex += 2;
- QuestionClass = ReadInt2(src, srcIndex);
- srcIndex += 2;
- return srcIndex - start;
- }
-
- internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- if (RecordName == QuestionName)
- {
- dst[dstIndex++] = unchecked(unchecked(0xC0));
- // label string pointer to
- dst[dstIndex++] = unchecked(unchecked(0x0C));
- }
- else
- {
- // questionName (offset 12)
- dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
- }
- WriteInt2(RecordType, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(RecordClass, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(Ttl, dst, dstIndex);
- dstIndex += 4;
- RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
- WriteInt2(RDataLength, dst, dstIndex);
- dstIndex += 2 + RDataLength;
- return dstIndex - start;
- }
-
- internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- int end;
- if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
- {
- RecordName = QuestionName;
- // label string pointer to questionName
- srcIndex += 2;
- }
- else
- {
- srcIndex += RecordName.ReadWireFormat(src, srcIndex);
- }
- RecordType = ReadInt2(src, srcIndex);
- srcIndex += 2;
- RecordClass = ReadInt2(src, srcIndex);
- srcIndex += 2;
- Ttl = ReadInt4(src, srcIndex);
- srcIndex += 4;
- RDataLength = ReadInt2(src, srcIndex);
- srcIndex += 2;
- AddrEntry = new NbtAddress[RDataLength / 6];
- end = srcIndex + RDataLength;
- for (AddrIndex = 0; srcIndex < end; AddrIndex++)
- {
- srcIndex += ReadRDataWireFormat(src, srcIndex);
- }
- return srcIndex - start;
- }
-
- internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
-
- internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
-
- public override string ToString()
- {
- string opCodeString;
- string resultCodeString;
- string questionTypeString;
- string recordTypeString;
-
- switch (OpCode)
- {
- case Query:
- {
- opCodeString = "QUERY";
- break;
- }
-
- case Wack:
- {
- opCodeString = "WACK";
- break;
- }
-
- default:
- {
- opCodeString = Extensions.ToString(OpCode);
- break;
- }
- }
- switch (ResultCode)
- {
- case FmtErr:
- {
- resultCodeString = "FMT_ERR";
- break;
- }
-
- case SrvErr:
- {
- resultCodeString = "SRV_ERR";
- break;
- }
-
- case ImpErr:
- {
- resultCodeString = "IMP_ERR";
- break;
- }
-
- case RfsErr:
- {
- resultCodeString = "RFS_ERR";
- break;
- }
-
- case ActErr:
- {
- resultCodeString = "ACT_ERR";
- break;
- }
-
- case CftErr:
- {
- resultCodeString = "CFT_ERR";
- break;
- }
-
- default:
- {
- resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
- break;
- }
- }
- switch (QuestionType)
- {
- case Nb:
- {
- questionTypeString = "NB";
- break;
- }
-
- case Nbstat:
- {
- questionTypeString = "NBSTAT";
- break;
- }
-
- default:
- {
- questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
- break;
- }
- }
- switch (RecordType)
- {
- case A:
- {
- recordTypeString = "A";
- break;
- }
-
- case Ns:
- {
- recordTypeString = "NS";
- break;
- }
-
- case Null:
- {
- recordTypeString = "NULL";
- break;
- }
-
- case Nb:
- {
- recordTypeString = "NB";
- break;
- }
-
- case Nbstat:
- {
- recordTypeString = "NBSTAT";
- break;
- }
-
- default:
- {
- recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4);
- break;
- }
- }
- return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode="
- + opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated
- + ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired
- + ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount="
- + QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount
- + ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType="
- + questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" +
- Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType="
- + recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump
- .ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs
deleted file mode 100644
index c64d385f1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs
+++ /dev/null
@@ -1,920 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Linq;
-using System.Net;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-using Extensions = SharpCifs.Util.Sharpen.Extensions;
-
-namespace SharpCifs.Netbios
-{
- /// <summary>This class represents a NetBIOS over TCP/IP address.</summary>
- /// <remarks>
- /// This class represents a NetBIOS over TCP/IP address. Under normal
- /// conditions, users of jCIFS need not be concerned with this class as
- /// name resolution and session services are handled internally by the smb package.
- /// <p> Applications can use the methods <code>getLocalHost</code>,
- /// <code>getByName</code>, and
- /// <code>getAllByAddress</code> to create a new NbtAddress instance. This
- /// class is symmetric with
- /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
- /// .
- /// <p><b>About NetBIOS:</b> The NetBIOS name
- /// service is a dynamic distributed service that allows hosts to resolve
- /// names by broadcasting a query, directing queries to a server such as
- /// Samba or WINS. NetBIOS is currently the primary networking layer for
- /// providing name service, datagram service, and session service to the
- /// Microsoft Windows platform. A NetBIOS name can be 15 characters long
- /// and hosts usually registers several names on the network. From a
- /// Windows command prompt you can see
- /// what names a host registers with the nbtstat command.
- /// <p><blockquote><pre>
- /// C:\&gt;nbtstat -a 192.168.1.15
- /// NetBIOS Remote Machine Name Table
- /// Name Type Status
- /// ---------------------------------------------
- /// JMORRIS2 <00> UNIQUE Registered
- /// BILLING-NY <00> GROUP Registered
- /// JMORRIS2 <03> UNIQUE Registered
- /// JMORRIS2 <20> UNIQUE Registered
- /// BILLING-NY <1E> GROUP Registered
- /// JMORRIS <03> UNIQUE Registered
- /// MAC Address = 00-B0-34-21-FA-3B
- /// </blockquote></pre>
- /// <p> The hostname of this machine is <code>JMORRIS2</code>. It is
- /// a member of the group(a.k.a workgroup and domain) <code>BILLING-NY</code>. To
- /// obtain an
- /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
- /// for a host one might do:
- /// <pre>
- /// InetAddress addr = NbtAddress.getByName( "jmorris2" ).getInetAddress();
- /// </pre>
- /// <p>From a UNIX platform with Samba installed you can perform similar
- /// diagnostics using the <code>nmblookup</code> utility.
- /// </remarks>
- /// <author>Michael B. Allen</author>
- /// <seealso cref="System.Net.IPAddress">System.Net.IPAddress</seealso>
- /// <since>jcifs-0.1</since>
- public sealed class NbtAddress
- {
- internal static readonly string AnyHostsName = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
-
- /// <summary>
- /// This is a special name for querying the master browser that serves the
- /// list of hosts found in "Network Neighborhood".
- /// </summary>
- /// <remarks>
- /// This is a special name for querying the master browser that serves the
- /// list of hosts found in "Network Neighborhood".
- /// </remarks>
- public static readonly string MasterBrowserName = "\u0001\u0002__MSBROWSE__\u0002";
-
- /// <summary>
- /// A special generic name specified when connecting to a host for which
- /// a name is not known.
- /// </summary>
- /// <remarks>
- /// A special generic name specified when connecting to a host for which
- /// a name is not known. Not all servers respond to this name.
- /// </remarks>
- public static readonly string SmbserverName = "*SMBSERVER ";
-
- /// <summary>A B node only broadcasts name queries.</summary>
- /// <remarks>
- /// A B node only broadcasts name queries. This is the default if a
- /// nameserver such as WINS or Samba is not specified.
- /// </remarks>
- public const int BNode = 0;
-
- /// <summary>
- /// A Point-to-Point node, or P node, unicasts queries to a nameserver
- /// only.
- /// </summary>
- /// <remarks>
- /// A Point-to-Point node, or P node, unicasts queries to a nameserver
- /// only. Natrually the <code>jcifs.netbios.nameserver</code> property must
- /// be set.
- /// </remarks>
- public const int PNode = 1;
-
- /// <summary>
- /// Try Broadcast queries first, then try to resolve the name using the
- /// nameserver.
- /// </summary>
- /// <remarks>
- /// Try Broadcast queries first, then try to resolve the name using the
- /// nameserver.
- /// </remarks>
- public const int MNode = 2;
-
- /// <summary>A Hybrid node tries to resolve a name using the nameserver first.</summary>
- /// <remarks>
- /// A Hybrid node tries to resolve a name using the nameserver first. If
- /// that fails use the broadcast address. This is the default if a nameserver
- /// is provided. This is the behavior of Microsoft Windows machines.
- /// </remarks>
- public const int HNode = 3;
-
- internal static readonly IPAddress[] Nbns = Config.GetInetAddressArray("jcifs.netbios.wins"
- , ",", new IPAddress[0]);
-
- private static readonly NameServiceClient Client = new NameServiceClient();
-
- private const int DefaultCachePolicy = 30;
-
- private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
- , DefaultCachePolicy);
-
- private const int Forever = -1;
-
- private static int _nbnsIndex;
-
- private static readonly Hashtable AddressCache = new Hashtable();
-
- private static readonly Hashtable LookupTable = new Hashtable();
-
- internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null);
-
- internal static readonly NbtAddress UnknownAddress = new NbtAddress
- (UnknownName, 0, false, BNode);
-
- internal static readonly byte[] UnknownMacAddress = { unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)) };
-
- internal sealed class CacheEntry
- {
- internal Name HostName;
-
- internal NbtAddress Address;
-
- internal long Expiration;
-
- internal CacheEntry(Name hostName, NbtAddress address, long expiration)
- {
- this.HostName = hostName;
- this.Address = address;
- this.Expiration = expiration;
- }
- }
-
- internal static NbtAddress Localhost;
-
- static NbtAddress()
- {
- IPAddress localInetAddress;
- string localHostname;
- Name localName;
- AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
- , Forever));
- localInetAddress = Client.laddr;
- if (localInetAddress == null)
- {
- try
- {
- localInetAddress = Extensions.GetAddressByName("127.0.0.1");
- }
- catch (UnknownHostException)
- {
-
- }
- }
- localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
- if (string.IsNullOrEmpty(localHostname))
- {
- byte[] addr = localInetAddress.GetAddressBytes();
-
- /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
- (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
- (int)(0xFF))), 2);*/
- localHostname = "JCIFS_127_0_0_1";
- }
- localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope"
- , null));
- Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
- , false, false, true, false, UnknownMacAddress);
- CacheAddress(localName, Localhost, Forever);
- }
-
- internal static void CacheAddress(Name hostName, NbtAddress addr)
- {
- if (CachePolicy == 0)
- {
- return;
- }
- long expiration = -1;
- if (CachePolicy != Forever)
- {
- expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
- }
- CacheAddress(hostName, addr, expiration);
- }
-
- internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
- )
- {
- if (CachePolicy == 0)
- {
- return;
- }
- lock (AddressCache)
- {
- CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
- if (entry == null)
- {
- entry = new CacheEntry(hostName, addr, expiration);
- AddressCache.Put(hostName, entry);
- }
- else
- {
- entry.Address = addr;
- entry.Expiration = expiration;
- }
- }
- }
-
- internal static void CacheAddressArray(NbtAddress[] addrs)
- {
- if (CachePolicy == 0)
- {
- return;
- }
- long expiration = -1;
- if (CachePolicy != Forever)
- {
- expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
- }
- lock (AddressCache)
- {
- for (int i = 0; i < addrs.Length; i++)
- {
- CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName
- );
- if (entry == null)
- {
- entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration);
- AddressCache.Put(addrs[i].HostName, entry);
- }
- else
- {
- entry.Address = addrs[i];
- entry.Expiration = expiration;
- }
- }
- }
- }
-
- internal static NbtAddress GetCachedAddress(Name hostName)
- {
- if (CachePolicy == 0)
- {
- return null;
- }
- lock (AddressCache)
- {
- CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
- if (entry != null && entry.Expiration < Runtime.CurrentTimeMillis() && entry.Expiration
- >= 0)
- {
- entry = null;
- }
- return entry != null ? entry.Address : null;
- }
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal static NbtAddress DoNameQuery(Name name, IPAddress svr)
- {
- NbtAddress addr;
- if (name.HexCode == unchecked(0x1d) && svr == null)
- {
- svr = Client.Baddr;
- }
- // bit of a hack but saves a lookup
- name.SrcHashCode = svr != null ? svr.GetHashCode() : 0;
- addr = GetCachedAddress(name);
- if (addr == null)
- {
- if ((addr = (NbtAddress)CheckLookupTable(name)) == null)
- {
- try
- {
- addr = Client.GetByName(name, svr);
- }
- catch (UnknownHostException)
- {
- addr = UnknownAddress;
- }
- finally
- {
- CacheAddress(name, addr);
- UpdateLookupTable(name);
- }
- }
- }
- if (addr == UnknownAddress)
- {
- throw new UnknownHostException(name.ToString());
- }
- return addr;
- }
-
- private static object CheckLookupTable(Name name)
- {
- object obj;
- lock (LookupTable)
- {
- if (LookupTable.ContainsKey(name) == false)
- {
- LookupTable.Put(name, name);
- return null;
- }
- while (LookupTable.ContainsKey(name))
- {
- try
- {
- Runtime.Wait(LookupTable);
- }
- catch (Exception)
- {
- }
- }
- }
- obj = GetCachedAddress(name);
- if (obj == null)
- {
- lock (LookupTable)
- {
- LookupTable.Put(name, name);
- }
- }
- return obj;
- }
-
- private static void UpdateLookupTable(Name name)
- {
- lock (LookupTable)
- {
- //Sharpen.Collections.Remove(LOOKUP_TABLE, name);
- LookupTable.Remove(name);
- Runtime.NotifyAll(LookupTable);
- }
- }
-
- /// <summary>Retrieves the local host address.</summary>
- /// <remarks>Retrieves the local host address.</remarks>
- /// <exception cref="UnknownHostException">
- /// This is not likely as the IP returned
- /// by <code>InetAddress</code> should be available
- /// </exception>
- public static NbtAddress GetLocalHost()
- {
- return Localhost;
- }
-
- public static NbtAddress[] GetHosts()
- {
- return new NameServiceClient().GetHosts();
- }
-
- public static Name GetLocalName()
- {
- return Localhost.HostName;
- }
-
- /// <summary>Determines the address of a host given it's host name.</summary>
- /// <remarks>
- /// Determines the address of a host given it's host name. The name can be a NetBIOS name like
- /// "freto" or an IP address like "192.168.1.15". It cannot be a DNS name;
- /// the analygous
- /// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
- /// or
- /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
- /// <code>getByName</code> methods can be used for that.
- /// </remarks>
- /// <param name="host">hostname to resolve</param>
- /// <exception cref="UnknownHostException">if there is an error resolving the name
- /// </exception>
- public static NbtAddress GetByName(string host)
- {
- return GetByName(host, unchecked(0x00), null);
- }
-
- /// <summary>Determines the address of a host given it's host name.</summary>
- /// <remarks>
- /// Determines the address of a host given it's host name. NetBIOS
- /// names also have a <code>type</code>. Types(aka Hex Codes)
- /// are used to distiquish the various services on a host. &lt;a
- /// href="../../../nbtcodes.html"&gt;Here</a> is
- /// a fairly complete list of NetBIOS hex codes. Scope is not used but is
- /// still functional in other NetBIOS products and so for completeness it has been
- /// implemented. A <code>scope</code> of <code>null</code> or <code>""</code>
- /// signifies no scope.
- /// </remarks>
- /// <param name="host">the name to resolve</param>
- /// <param name="type">the hex code of the name</param>
- /// <param name="scope">the scope of the name</param>
- /// <exception cref="UnknownHostException">if there is an error resolving the name
- /// </exception>
- public static NbtAddress GetByName(string host, int type, string scope)
- {
- return GetByName(host, type, scope, null);
- }
-
- /// <exception cref="UnknownHostException"></exception>
- public static NbtAddress GetByName(string host, int type, string scope, IPAddress
- svr)
- {
- if (string.IsNullOrEmpty(host))
- {
- return GetLocalHost();
- }
- if (!char.IsDigit(host[0]))
- {
- return DoNameQuery(new Name(host, type, scope), svr);
- }
- int ip = unchecked(0x00);
- int hitDots = 0;
- char[] data = host.ToCharArray();
- for (int i = 0; i < data.Length; i++)
- {
- char c = data[i];
- if (c < 48 || c > 57)
- {
- return DoNameQuery(new Name(host, type, scope), svr);
- }
- int b = unchecked(0x00);
- while (c != '.')
- {
- if (c < 48 || c > 57)
- {
- return DoNameQuery(new Name(host, type, scope), svr);
- }
- b = b * 10 + c - '0';
- if (++i >= data.Length)
- {
- break;
- }
- c = data[i];
- }
- if (b > unchecked(0xFF))
- {
- return DoNameQuery(new Name(host, type, scope), svr);
- }
- ip = (ip << 8) + b;
- hitDots++;
- }
- if (hitDots != 4 || host.EndsWith("."))
- {
- return DoNameQuery(new Name(host, type, scope), svr);
- }
- return new NbtAddress(UnknownName, ip, false, BNode);
- }
-
- /// <exception cref="UnknownHostException"></exception>
- public static NbtAddress[] GetAllByName(string host, int type, string scope, IPAddress
- svr)
- {
- return Client.GetAllByName(new Name(host, type, scope), svr);
- }
-
- /// <summary>Retrieve all addresses of a host by it's address.</summary>
- /// <remarks>
- /// Retrieve all addresses of a host by it's address. NetBIOS hosts can
- /// have many names for a given IP address. The name and IP address make the
- /// NetBIOS address. This provides a way to retrieve the other names for a
- /// host with the same IP address.
- /// </remarks>
- /// <param name="host">hostname to lookup all addresses for</param>
- /// <exception cref="UnknownHostException">if there is an error resolving the name
- /// </exception>
- public static NbtAddress[] GetAllByAddress(string host)
- {
- return GetAllByAddress(GetByName(host, unchecked(0x00), null));
- }
-
- /// <summary>Retrieve all addresses of a host by it's address.</summary>
- /// <remarks>
- /// Retrieve all addresses of a host by it's address. NetBIOS hosts can
- /// have many names for a given IP address. The name and IP address make
- /// the NetBIOS address. This provides a way to retrieve the other names
- /// for a host with the same IP address. See
- /// <see cref="GetByName(string)">GetByName(string)</see>
- /// for a description of <code>type</code>
- /// and <code>scope</code>.
- /// </remarks>
- /// <param name="host">hostname to lookup all addresses for</param>
- /// <param name="type">the hexcode of the name</param>
- /// <param name="scope">the scope of the name</param>
- /// <exception cref="UnknownHostException">if there is an error resolving the name
- /// </exception>
- public static NbtAddress[] GetAllByAddress(string host, int type, string scope)
- {
- return GetAllByAddress(GetByName(host, type, scope));
- }
-
- /// <summary>Retrieve all addresses of a host by it's address.</summary>
- /// <remarks>
- /// Retrieve all addresses of a host by it's address. NetBIOS hosts can
- /// have many names for a given IP address. The name and IP address make the
- /// NetBIOS address. This provides a way to retrieve the other names for a
- /// host with the same IP address.
- /// </remarks>
- /// <param name="addr">the address to query</param>
- /// <exception cref="UnknownHostException">if address cannot be resolved</exception>
- public static NbtAddress[] GetAllByAddress(NbtAddress addr)
- {
- try
- {
- NbtAddress[] addrs = Client.GetNodeStatus(addr);
- CacheAddressArray(addrs);
- return addrs;
- }
- catch (UnknownHostException)
- {
- throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
- HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
- == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
- + addr.GetHostAddress());
- }
- }
-
- public static IPAddress GetWinsAddress()
- {
- return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
- }
-
- public static bool IsWins(IPAddress svr)
- {
- for (int i = 0; svr != null && i < Nbns.Length; i++)
- {
- if (svr.GetHashCode() == Nbns[i].GetHashCode())
- {
- return true;
- }
- }
- return false;
- }
-
- internal static IPAddress SwitchWins()
- {
- _nbnsIndex = (_nbnsIndex + 1) < Nbns.Length ? _nbnsIndex + 1 : 0;
- return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
- }
-
- internal Name HostName;
-
- internal int Address;
-
- internal int NodeType;
-
- internal bool GroupName;
-
- internal bool isBeingDeleted;
-
- internal bool isInConflict;
-
- internal bool isActive;
-
- internal bool isPermanent;
-
- internal bool IsDataFromNodeStatus;
-
- internal byte[] MacAddress;
-
- internal string CalledName;
-
- internal NbtAddress(Name hostName, int address, bool groupName, int nodeType)
- {
- this.HostName = hostName;
- this.Address = address;
- this.GroupName = groupName;
- this.NodeType = nodeType;
- }
-
- internal NbtAddress(Name hostName, int address, bool groupName, int nodeType, bool
- isBeingDeleted, bool isInConflict, bool isActive, bool isPermanent, byte[] macAddress
- )
- {
- this.HostName = hostName;
- this.Address = address;
- this.GroupName = groupName;
- this.NodeType = nodeType;
- this.isBeingDeleted = isBeingDeleted;
- this.isInConflict = isInConflict;
- this.isActive = isActive;
- this.isPermanent = isPermanent;
- this.MacAddress = macAddress;
- IsDataFromNodeStatus = true;
- }
-
- public string FirstCalledName()
- {
- CalledName = HostName.name;
- if (char.IsDigit(CalledName[0]))
- {
- int i;
- int len;
- int dots;
- char[] data;
- i = dots = 0;
- len = CalledName.Length;
- data = CalledName.ToCharArray();
- while (i < len && char.IsDigit(data[i++]))
- {
- if (i == len && dots == 3)
- {
- // probably an IP address
- CalledName = SmbserverName;
- break;
- }
- if (i < len && data[i] == '.')
- {
- dots++;
- i++;
- }
- }
- }
- else
- {
- switch (HostName.HexCode)
- {
- case unchecked(0x1B):
- case unchecked(0x1C):
- case unchecked(0x1D):
- {
- CalledName = SmbserverName;
- break;
- }
- }
- }
- return CalledName;
- }
-
- public string NextCalledName()
- {
- if (CalledName == HostName.name)
- {
- CalledName = SmbserverName;
- }
- else
- {
- if (CalledName == SmbserverName)
- {
- NbtAddress[] addrs;
- try
- {
- addrs = Client.GetNodeStatus(this);
- if (HostName.HexCode == unchecked(0x1D))
- {
- for (int i = 0; i < addrs.Length; i++)
- {
- if (addrs[i].HostName.HexCode == unchecked(0x20))
- {
- return addrs[i].HostName.name;
- }
- }
- return null;
- }
- if (IsDataFromNodeStatus)
- {
- CalledName = null;
- return HostName.name;
- }
- }
- catch (UnknownHostException)
- {
- CalledName = null;
- }
- }
- else
- {
- CalledName = null;
- }
- }
- return CalledName;
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal void CheckData()
- {
- if (HostName == UnknownName)
- {
- GetAllByAddress(this);
- }
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal void CheckNodeStatusData()
- {
- if (IsDataFromNodeStatus == false)
- {
- GetAllByAddress(this);
- }
- }
-
- /// <summary>Determines if the address is a group address.</summary>
- /// <remarks>
- /// Determines if the address is a group address. This is also
- /// known as a workgroup name or group name.
- /// </remarks>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public bool IsGroupAddress()
- {
- CheckData();
- return GroupName;
- }
-
- /// <summary>Checks the node type of this address.</summary>
- /// <remarks>Checks the node type of this address.</remarks>
- /// <returns>
- ///
- /// <see cref="BNode">B_NODE</see>
- /// ,
- /// <see cref="PNode">P_NODE</see>
- /// ,
- /// <see cref="MNode">M_NODE</see>
- /// ,
- /// <see cref="HNode">H_NODE</see>
- /// </returns>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public int GetNodeType()
- {
- CheckData();
- return NodeType;
- }
-
- /// <summary>Determines if this address in the process of being deleted.</summary>
- /// <remarks>Determines if this address in the process of being deleted.</remarks>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public bool IsBeingDeleted()
- {
- CheckNodeStatusData();
- return isBeingDeleted;
- }
-
- /// <summary>Determines if this address in conflict with another address.</summary>
- /// <remarks>Determines if this address in conflict with another address.</remarks>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public bool IsInConflict()
- {
- CheckNodeStatusData();
- return isInConflict;
- }
-
- /// <summary>Determines if this address is active.</summary>
- /// <remarks>Determines if this address is active.</remarks>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public bool IsActive()
- {
- CheckNodeStatusData();
- return isActive;
- }
-
- /// <summary>Determines if this address is set to be permanent.</summary>
- /// <remarks>Determines if this address is set to be permanent.</remarks>
- /// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
- /// </exception>
- public bool IsPermanent()
- {
- CheckNodeStatusData();
- return isPermanent;
- }
-
- /// <summary>Retrieves the MAC address of the remote network interface.</summary>
- /// <remarks>Retrieves the MAC address of the remote network interface. Samba returns all zeros.
- /// </remarks>
- /// <returns>the MAC address as an array of six bytes</returns>
- /// <exception cref="UnknownHostException">
- /// if the host cannot be resolved to
- /// determine the MAC address.
- /// </exception>
- public byte[] GetMacAddress()
- {
- CheckNodeStatusData();
- return MacAddress;
- }
-
- /// <summary>The hostname of this address.</summary>
- /// <remarks>
- /// The hostname of this address. If the hostname is null the local machines
- /// IP address is returned.
- /// </remarks>
- /// <returns>the text representation of the hostname associated with this address</returns>
- public string GetHostName()
- {
- if (HostName == UnknownName)
- {
- return GetHostAddress();
- }
- return HostName.name;
- }
-
- /// <summary>Returns the raw IP address of this NbtAddress.</summary>
- /// <remarks>
- /// Returns the raw IP address of this NbtAddress. The result is in network
- /// byte order: the highest order byte of the address is in getAddress()[0].
- /// </remarks>
- /// <returns>a four byte array</returns>
- public byte[] GetAddress()
- {
- byte[] addr = new byte[4];
- addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF
- )));
- addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF
- )));
- addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF)
- ));
- addr[3] = unchecked((byte)(Address & unchecked(0xFF)));
- return addr;
- }
-
- /// <summary>To convert this address to an <code>InetAddress</code>.</summary>
- /// <remarks>To convert this address to an <code>InetAddress</code>.</remarks>
- /// <returns>
- /// the
- /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
- /// representation of this address.
- /// </returns>
- /// <exception cref="UnknownHostException"></exception>
- public IPAddress GetInetAddress()
- {
- return Extensions.GetAddressByName(GetHostAddress());
- }
-
- /// <summary>
- /// Returns this IP adress as a
- /// <see cref="string">string</see>
- /// in the form "%d.%d.%d.%d".
- /// </summary>
- public string GetHostAddress()
- {
- return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) + "." + (((int)(
- ((uint)Address) >> 16)) & unchecked(0xFF)) + "." + (((int)(((uint)Address
- ) >> 8)) & unchecked(0xFF)) + "." + (((int)(((uint)Address) >> 0)) & unchecked(
- 0xFF));
- }
-
- /// <summary>Returned the hex code associated with this name(e.g.</summary>
- /// <remarks>Returned the hex code associated with this name(e.g. 0x20 is for the file service)
- /// </remarks>
- public int GetNameType()
- {
- return HostName.HexCode;
- }
-
- /// <summary>Returns a hashcode for this IP address.</summary>
- /// <remarks>
- /// Returns a hashcode for this IP address. The hashcode comes from the IP address
- /// and is not generated from the string representation. So because NetBIOS nodes
- /// can have many names, all names associated with an IP will have the same
- /// hashcode.
- /// </remarks>
- public override int GetHashCode()
- {
- return Address;
- }
-
- /// <summary>Determines if this address is equal two another.</summary>
- /// <remarks>
- /// Determines if this address is equal two another. Only the IP Addresses
- /// are compared. Similar to the
- /// <see cref="GetHashCode()">GetHashCode()</see>
- /// method, the comparison
- /// is based on the integer IP address and not the string representation.
- /// </remarks>
- public override bool Equals(object obj)
- {
- return (obj != null) && (obj is NbtAddress) && (((NbtAddress)obj).Address == Address
- );
- }
-
- /// <summary>
- /// Returns the
- /// <see cref="string">string</see>
- /// representaion of this address.
- /// </summary>
- public override string ToString()
- {
- return HostName + "/" + GetHostAddress();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs
deleted file mode 100644
index e785c9943..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs
+++ /dev/null
@@ -1,164 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-
-namespace SharpCifs.Netbios
-{
-
- public class NbtException : IOException
- {
- public const int Success = 0;
-
- public const int ErrNamSrvc = unchecked(0x01);
-
- public const int ErrSsnSrvc = unchecked(0x02);
-
- public const int FmtErr = unchecked(0x1);
-
- public const int SrvErr = unchecked(0x2);
-
- public const int ImpErr = unchecked(0x4);
-
- public const int RfsErr = unchecked(0x5);
-
- public const int ActErr = unchecked(0x6);
-
- public const int CftErr = unchecked(0x7);
-
- public const int ConnectionRefused = -1;
-
- public const int NotListeningCalled = unchecked(0x80);
-
- public const int NotListeningCalling = unchecked(0x81);
-
- public const int CalledNotPresent = unchecked(0x82);
-
- public const int NoResources = unchecked(0x83);
-
- public const int Unspecified = unchecked(0x8F);
-
- public int ErrorClass;
-
- public int ErrorCode;
-
- // error classes
- // name service error codes
- // session service error codes
- public static string GetErrorString(int errorClass, int errorCode)
- {
- string result = string.Empty;
- switch (errorClass)
- {
- case Success:
- {
- result += "SUCCESS";
- break;
- }
-
- case ErrNamSrvc:
- {
- result += "ERR_NAM_SRVC/";
- switch (errorCode)
- {
- case FmtErr:
- {
- result += "FMT_ERR: Format Error";
- goto default;
- }
-
- default:
- {
- result += "Unknown error code: " + errorCode;
- break;
- }
- }
- break;
- }
-
- case ErrSsnSrvc:
- {
- result += "ERR_SSN_SRVC/";
- switch (errorCode)
- {
- case ConnectionRefused:
- {
- result += "Connection refused";
- break;
- }
-
- case NotListeningCalled:
- {
- result += "Not listening on called name";
- break;
- }
-
- case NotListeningCalling:
- {
- result += "Not listening for calling name";
- break;
- }
-
- case CalledNotPresent:
- {
- result += "Called name not present";
- break;
- }
-
- case NoResources:
- {
- result += "Called name present, but insufficient resources";
- break;
- }
-
- case Unspecified:
- {
- result += "Unspecified error";
- break;
- }
-
- default:
- {
- result += "Unknown error code: " + errorCode;
- break;
- }
- }
- break;
- }
-
- default:
- {
- result += "unknown error class: " + errorClass;
- break;
- }
- }
- return result;
- }
-
- public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
- , errorCode))
- {
- this.ErrorClass = errorClass;
- this.ErrorCode = errorCode;
- }
-
- public override string ToString()
- {
- return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString="
- + GetErrorString(ErrorClass, ErrorCode);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs
deleted file mode 100644
index 66d3bb3e5..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Netbios
-{
- internal class NodeStatusRequest : NameServicePacket
- {
- internal NodeStatusRequest(Name name)
- {
- QuestionName = name;
- QuestionType = Nbstat;
- IsRecurDesired = false;
- IsBroadcast = false;
- }
-
- internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
- {
- int tmp = QuestionName.HexCode;
- QuestionName.HexCode = unchecked(0x00);
- // type has to be 0x00 for node status
- int result = WriteQuestionSectionWireFormat(dst, dstIndex);
- QuestionName.HexCode = tmp;
- return result;
- }
-
- internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
- {
- return 0;
- }
-
- internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "NodeStatusRequest[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs
deleted file mode 100644
index aa3214419..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- internal class NodeStatusResponse : NameServicePacket
- {
- private NbtAddress _queryAddress;
-
- private int _numberOfNames;
-
- private byte[] _macAddress;
-
- private byte[] _stats;
-
- internal NbtAddress[] AddressArray;
-
- internal NodeStatusResponse(NbtAddress queryAddress)
- {
- this._queryAddress = queryAddress;
- RecordName = new Name();
- _macAddress = new byte[6];
- }
-
- internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
- {
- return ReadResourceRecordWireFormat(src, srcIndex);
- }
-
- internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- _numberOfNames = src[srcIndex] & unchecked(0xFF);
- int namesLength = _numberOfNames * 18;
- int statsLength = RDataLength - namesLength - 1;
- _numberOfNames = src[srcIndex++] & unchecked(0xFF);
- // gotta read the mac first so we can populate addressArray with it
- Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6);
- srcIndex += ReadNodeNameArray(src, srcIndex);
- _stats = new byte[statsLength];
- Array.Copy(src, srcIndex, _stats, 0, statsLength);
- srcIndex += statsLength;
- return srcIndex - start;
- }
-
- private int ReadNodeNameArray(byte[] src, int srcIndex)
- {
- int start = srcIndex;
- AddressArray = new NbtAddress[_numberOfNames];
- string n;
- int hexCode;
- string scope = _queryAddress.HostName.Scope;
- bool groupName;
- int ownerNodeType;
- bool isBeingDeleted;
- bool isInConflict;
- bool isActive;
- bool isPermanent;
- int j;
- bool addrFound = false;
- try
- {
- for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
- {
- for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
- {
- }
- n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
- );
- hexCode = src[srcIndex + 15] & unchecked(0xFF);
- groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
- ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5;
- isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
- isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false;
- isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false;
- isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false;
- if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
- == NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
- {
- if (_queryAddress.HostName == NbtAddress.UnknownName)
- {
- _queryAddress.HostName = new Name(n, hexCode, scope);
- }
- _queryAddress.GroupName = groupName;
- _queryAddress.NodeType = ownerNodeType;
- _queryAddress.isBeingDeleted = isBeingDeleted;
- _queryAddress.isInConflict = isInConflict;
- _queryAddress.isActive = isActive;
- _queryAddress.isPermanent = isPermanent;
- _queryAddress.MacAddress = _macAddress;
- _queryAddress.IsDataFromNodeStatus = true;
- addrFound = true;
- AddressArray[i] = _queryAddress;
- }
- else
- {
- AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
- , groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
- _macAddress);
- }
- }
- }
- catch (UnsupportedEncodingException)
- {
- }
- return srcIndex - start;
- }
-
- public override string ToString()
- {
- return "NodeStatusResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs
deleted file mode 100644
index a5243f7aa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- public class SessionRequestPacket : SessionServicePacket
- {
- private Name _calledName;
-
- private Name _callingName;
-
- public SessionRequestPacket()
- {
- _calledName = new Name();
- _callingName = new Name();
- }
-
- public SessionRequestPacket(Name calledName, Name callingName)
- {
- Type = SessionRequest;
- this._calledName = calledName;
- this._callingName = callingName;
- }
-
- internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dstIndex += _calledName.WriteWireFormat(dst, dstIndex);
- dstIndex += _callingName.WriteWireFormat(dst, dstIndex);
- return dstIndex - start;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- if (@in.Read(buffer, bufferIndex, Length) != Length)
- {
- throw new IOException("invalid session request wire format");
- }
- bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex);
- bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex);
- return bufferIndex - start;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs
deleted file mode 100644
index c901c6e26..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- internal class SessionRetargetResponsePacket : SessionServicePacket
- {
- private NbtAddress _retargetAddress;
-
- private int _retargetPort;
-
- public SessionRetargetResponsePacket()
- {
- Type = SessionRetargetResponse;
- Length = 6;
- }
-
- internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
- )
- {
- if (@in.Read(buffer, bufferIndex, Length) != Length)
- {
- throw new IOException("unexpected EOF reading netbios retarget session response");
- }
- int addr = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- _retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
- _retargetPort = ReadInt2(buffer, bufferIndex);
- return Length;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs
deleted file mode 100644
index c8d194222..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Netbios
-{
- public abstract class SessionServicePacket
- {
- internal const int SessionMessage = unchecked(0x00);
-
- internal const int SessionRequest = unchecked(0x81);
-
- public const int PositiveSessionResponse = unchecked(0x82);
-
- public const int NegativeSessionResponse = unchecked(0x83);
-
- internal const int SessionRetargetResponse = unchecked(0x84);
-
- internal const int SessionKeepAlive = unchecked(0x85);
-
- internal const int MaxMessageSize = unchecked(0x0001FFFF);
-
- internal const int HeaderLength = 4;
-
- // session service packet types
- internal static void WriteInt2(int val, byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
- dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
- }
-
- internal static void WriteInt4(int val, byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
- dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
- }
-
- internal static int ReadInt2(byte[] src, int srcIndex)
- {
- return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
- 0xFF));
- }
-
- internal static int ReadInt4(byte[] src, int srcIndex)
- {
- return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
- 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
- [srcIndex + 3] & unchecked(0xFF));
- }
-
- internal static int ReadLength(byte[] src, int srcIndex)
- {
- srcIndex++;
- return ((src[srcIndex++] & unchecked(0x01)) << 16) + ((src[srcIndex++] & unchecked(
- 0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF));
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static int Readn(InputStream @in, byte[] b, int off, int len)
- {
- int i = 0;
- int n;
- while (i < len)
- {
- n = @in.Read(b, off + i, len - i);
- if (n <= 0)
- {
- break;
- }
- i += n;
- }
- return i;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex
- )
- {
- int n;
- if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
- {
- if (n == -1)
- {
- return -1;
- }
- throw new IOException("unexpected EOF reading netbios session header");
- }
- int t = buffer[bufferIndex] & unchecked(0xFF);
- return t;
- }
-
- internal int Type;
-
- internal int Length;
-
- public virtual int WriteWireFormat(byte[] dst, int dstIndex)
- {
- Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength);
- WriteHeaderWireFormat(dst, dstIndex);
- return HeaderLength + Length;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex
- )
- {
- ReadHeaderWireFormat(@in, buffer, bufferIndex);
- return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
- }
-
- internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = unchecked((byte)Type);
- if (Length > unchecked(0x0000FFFF))
- {
- dst[dstIndex] = unchecked(unchecked(0x01));
- }
- dstIndex++;
- WriteInt2(Length, dst, dstIndex);
- return HeaderLength;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex
- )
- {
- Type = buffer[bufferIndex++] & unchecked(0xFF);
- Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) + ReadInt2(buffer
- , bufferIndex + 1);
- return HeaderLength;
- }
-
- internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
-
- /// <exception cref="System.IO.IOException"></exception>
- internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
- );
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs
deleted file mode 100644
index 116f71b75..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs
+++ /dev/null
@@ -1,197 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Ntlmssp
-{
- /// <summary>Flags used during negotiation of NTLMSSP authentication.</summary>
- /// <remarks>Flags used during negotiation of NTLMSSP authentication.</remarks>
- public abstract class NtlmFlags
- {
- /// <summary>Indicates whether Unicode strings are supported or used.</summary>
- /// <remarks>Indicates whether Unicode strings are supported or used.</remarks>
- public const int NtlmsspNegotiateUnicode = unchecked(0x00000001);
-
- /// <summary>Indicates whether OEM strings are supported or used.</summary>
- /// <remarks>Indicates whether OEM strings are supported or used.</remarks>
- public const int NtlmsspNegotiateOem = unchecked(0x00000002);
-
- /// <summary>
- /// Indicates whether the authentication target is requested from
- /// the server.
- /// </summary>
- /// <remarks>
- /// Indicates whether the authentication target is requested from
- /// the server.
- /// </remarks>
- public const int NtlmsspRequestTarget = unchecked(0x00000004);
-
- /// <summary>
- /// Specifies that communication across the authenticated channel
- /// should carry a digital signature (message integrity).
- /// </summary>
- /// <remarks>
- /// Specifies that communication across the authenticated channel
- /// should carry a digital signature (message integrity).
- /// </remarks>
- public const int NtlmsspNegotiateSign = unchecked(0x00000010);
-
- /// <summary>
- /// Specifies that communication across the authenticated channel
- /// should be encrypted (message confidentiality).
- /// </summary>
- /// <remarks>
- /// Specifies that communication across the authenticated channel
- /// should be encrypted (message confidentiality).
- /// </remarks>
- public const int NtlmsspNegotiateSeal = unchecked(0x00000020);
-
- /// <summary>Indicates datagram authentication.</summary>
- /// <remarks>Indicates datagram authentication.</remarks>
- public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040);
-
- /// <summary>
- /// Indicates that the LAN Manager session key should be used for
- /// signing and sealing authenticated communication.
- /// </summary>
- /// <remarks>
- /// Indicates that the LAN Manager session key should be used for
- /// signing and sealing authenticated communication.
- /// </remarks>
- public const int NtlmsspNegotiateLmKey = unchecked(0x00000080);
-
- public const int NtlmsspNegotiateNetware = unchecked(0x00000100);
-
- /// <summary>Indicates support for NTLM authentication.</summary>
- /// <remarks>Indicates support for NTLM authentication.</remarks>
- public const int NtlmsspNegotiateNtlm = unchecked(0x00000200);
-
- /// <summary>
- /// Indicates whether the OEM-formatted domain name in which the
- /// client workstation has membership is supplied in the Type-1 message.
- /// </summary>
- /// <remarks>
- /// Indicates whether the OEM-formatted domain name in which the
- /// client workstation has membership is supplied in the Type-1 message.
- /// This is used in the negotation of local authentication.
- /// </remarks>
- public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000);
-
- /// <summary>
- /// Indicates whether the OEM-formatted workstation name is supplied
- /// in the Type-1 message.
- /// </summary>
- /// <remarks>
- /// Indicates whether the OEM-formatted workstation name is supplied
- /// in the Type-1 message. This is used in the negotiation of local
- /// authentication.
- /// </remarks>
- public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000);
-
- /// <summary>
- /// Sent by the server to indicate that the server and client are
- /// on the same machine.
- /// </summary>
- /// <remarks>
- /// Sent by the server to indicate that the server and client are
- /// on the same machine. This implies that the server will include
- /// a local security context handle in the Type 2 message, for
- /// use in local authentication.
- /// </remarks>
- public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000);
-
- /// <summary>
- /// Indicates that authenticated communication between the client
- /// and server should carry a "dummy" digital signature.
- /// </summary>
- /// <remarks>
- /// Indicates that authenticated communication between the client
- /// and server should carry a "dummy" digital signature.
- /// </remarks>
- public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000);
-
- /// <summary>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a domain.
- /// </summary>
- /// <remarks>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a domain.
- /// </remarks>
- public const int NtlmsspTargetTypeDomain = unchecked(0x00010000);
-
- /// <summary>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a server.
- /// </summary>
- /// <remarks>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a server.
- /// </remarks>
- public const int NtlmsspTargetTypeServer = unchecked(0x00020000);
-
- /// <summary>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a share (presumably for share-level
- /// authentication).
- /// </summary>
- /// <remarks>
- /// Sent by the server in the Type 2 message to indicate that the
- /// target authentication realm is a share (presumably for share-level
- /// authentication).
- /// </remarks>
- public const int NtlmsspTargetTypeShare = unchecked(0x00040000);
-
- /// <summary>
- /// Indicates that the NTLM2 signing and sealing scheme should be used
- /// for protecting authenticated communications.
- /// </summary>
- /// <remarks>
- /// Indicates that the NTLM2 signing and sealing scheme should be used
- /// for protecting authenticated communications. This refers to a
- /// particular session security scheme, and is not related to the use
- /// of NTLMv2 authentication.
- /// </remarks>
- public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000);
-
- public const int NtlmsspRequestInitResponse = unchecked(0x00100000);
-
- public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
-
- public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000
- );
-
- /// <summary>
- /// Sent by the server in the Type 2 message to indicate that it is
- /// including a Target Information block in the message.
- /// </summary>
- /// <remarks>
- /// Sent by the server in the Type 2 message to indicate that it is
- /// including a Target Information block in the message. The Target
- /// Information block is used in the calculation of the NTLMv2 response.
- /// </remarks>
- public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000);
-
- /// <summary>Indicates that 128-bit encryption is supported.</summary>
- /// <remarks>Indicates that 128-bit encryption is supported.</remarks>
- public const int NtlmsspNegotiate128 = unchecked(0x20000000);
-
- public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000);
-
- /// <summary>Indicates that 56-bit encryption is supported.</summary>
- /// <remarks>Indicates that 56-bit encryption is supported.</remarks>
- public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000));
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs
deleted file mode 100644
index 02827d2d0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Ntlmssp
-{
- /// <summary>Abstract superclass for all NTLMSSP messages.</summary>
- /// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
- public abstract class NtlmMessage : NtlmFlags
- {
- /// <summary>The NTLMSSP "preamble".</summary>
- /// <remarks>The NTLMSSP "preamble".</remarks>
- protected internal static readonly byte[] NtlmsspSignature = { unchecked(
- (byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')),
- unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte
- )('S')), unchecked((byte)('P')), unchecked(0) };
-
- private static readonly string OemEncoding = Config.DefaultOemEncoding;
-
- protected internal static readonly string UniEncoding = "UTF-16LE";
-
- private int _flags;
-
- /// <summary>Returns the flags currently in use for this message.</summary>
- /// <remarks>Returns the flags currently in use for this message.</remarks>
- /// <returns>
- /// An <code>int</code> containing the flags in use for this
- /// message.
- /// </returns>
- public virtual int GetFlags()
- {
- return _flags;
- }
-
- /// <summary>Sets the flags for this message.</summary>
- /// <remarks>Sets the flags for this message.</remarks>
- /// <param name="flags">The flags for this message.</param>
- public virtual void SetFlags(int flags)
- {
- this._flags = flags;
- }
-
- /// <summary>Returns the status of the specified flag.</summary>
- /// <remarks>Returns the status of the specified flag.</remarks>
- /// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param>
- /// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
- public virtual bool GetFlag(int flag)
- {
- return (GetFlags() & flag) != 0;
- }
-
- /// <summary>Sets or clears the specified flag.</summary>
- /// <remarks>Sets or clears the specified flag.</remarks>
- /// <param name="flag">
- /// The flag to set/clear (i.e.,
- /// <code>NTLMSSP_NEGOTIATE_OEM</code>).
- /// </param>
- /// <param name="value">
- /// Indicates whether to set (<code>true</code>) or
- /// clear (<code>false</code>) the specified flag.
- /// </param>
- public virtual void SetFlag(int flag, bool value)
- {
- SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff)
- ) ^ flag)));
- }
-
- internal static int ReadULong(byte[] src, int index)
- {
- return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index
- + 3] & unchecked(0xff)) << 24);
- }
-
- internal static int ReadUShort(byte[] src, int index)
- {
- return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
- }
-
- internal static byte[] ReadSecurityBuffer(byte[] src, int index)
- {
- int length = ReadUShort(src, index);
- int offset = ReadULong(src, index + 4);
- byte[] buffer = new byte[length];
- Array.Copy(src, offset, buffer, 0, length);
- return buffer;
- }
-
- internal static void WriteULong(byte[] dest, int offset, int value)
- {
- dest[offset] = unchecked((byte)(value & unchecked(0xff)));
- dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
- dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff)));
- dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff)));
- }
-
- internal static void WriteUShort(byte[] dest, int offset, int value)
- {
- dest[offset] = unchecked((byte)(value & unchecked(0xff)));
- dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
- }
-
- internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset,
- byte[] src)
- {
- int length = (src != null) ? src.Length : 0;
- if (length == 0)
- {
- return;
- }
- WriteUShort(dest, offset, length);
- WriteUShort(dest, offset + 2, length);
- WriteULong(dest, offset + 4, bodyOffset);
- Array.Copy(src, 0, dest, bodyOffset, length);
- }
-
- internal static string GetOemEncoding()
- {
- return OemEncoding;
- }
-
- /// <summary>Returns the raw byte representation of this message.</summary>
- /// <remarks>Returns the raw byte representation of this message.</remarks>
- /// <returns>A <code>byte[]</code> containing the raw message material.</returns>
- public abstract byte[] ToByteArray();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs
deleted file mode 100644
index afcf5ec7e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs
+++ /dev/null
@@ -1,249 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Netbios;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Ntlmssp
-{
- /// <summary>Represents an NTLMSSP Type-1 message.</summary>
- /// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
- public class Type1Message : NtlmMessage
- {
- private static readonly int DefaultFlags;
-
- private static readonly string DefaultDomain;
-
- private static readonly string DefaultWorkstation;
-
- private string _suppliedDomain;
-
- private string _suppliedWorkstation;
-
- static Type1Message()
- {
- DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
- , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
- DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
- string defaultWorkstation = null;
- try
- {
- defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
- }
- catch (UnknownHostException)
- {
- }
- DefaultWorkstation = defaultWorkstation;
- }
-
- /// <summary>
- /// Creates a Type-1 message using default values from the current
- /// environment.
- /// </summary>
- /// <remarks>
- /// Creates a Type-1 message using default values from the current
- /// environment.
- /// </remarks>
- public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation
- ())
- {
- }
-
- /// <summary>Creates a Type-1 message with the specified parameters.</summary>
- /// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
- /// <param name="flags">The flags to apply to this message.</param>
- /// <param name="suppliedDomain">The supplied authentication domain.</param>
- /// <param name="suppliedWorkstation">The supplied workstation name.</param>
- public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
- {
- SetFlags(GetDefaultFlags() | flags);
- SetSuppliedDomain(suppliedDomain);
- if (suppliedWorkstation == null)
- {
- suppliedWorkstation = GetDefaultWorkstation();
- }
- SetSuppliedWorkstation(suppliedWorkstation);
- }
-
- /// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary>
- /// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks>
- /// <param name="material">The raw Type-1 material used to construct this message.</param>
- /// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
- /// </exception>
- public Type1Message(byte[] material)
- {
- Parse(material);
- }
-
- /// <summary>Returns the supplied authentication domain.</summary>
- /// <remarks>Returns the supplied authentication domain.</remarks>
- /// <returns>A <code>String</code> containing the supplied domain.</returns>
- public virtual string GetSuppliedDomain()
- {
- return _suppliedDomain;
- }
-
- /// <summary>Sets the supplied authentication domain for this message.</summary>
- /// <remarks>Sets the supplied authentication domain for this message.</remarks>
- /// <param name="suppliedDomain">The supplied domain for this message.</param>
- public virtual void SetSuppliedDomain(string suppliedDomain)
- {
- this._suppliedDomain = suppliedDomain;
- }
-
- /// <summary>Returns the supplied workstation name.</summary>
- /// <remarks>Returns the supplied workstation name.</remarks>
- /// <returns>A <code>String</code> containing the supplied workstation name.</returns>
- public virtual string GetSuppliedWorkstation()
- {
- return _suppliedWorkstation;
- }
-
- /// <summary>Sets the supplied workstation name for this message.</summary>
- /// <remarks>Sets the supplied workstation name for this message.</remarks>
- /// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
- public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
- {
- this._suppliedWorkstation = suppliedWorkstation;
- }
-
- public override byte[] ToByteArray()
- {
- try
- {
- string suppliedDomain = GetSuppliedDomain();
- string suppliedWorkstation = GetSuppliedWorkstation();
- int flags = GetFlags();
- bool hostInfo = false;
- byte[] domain = new byte[0];
- if (!string.IsNullOrEmpty(suppliedDomain))
- {
- hostInfo = true;
- flags |= NtlmsspNegotiateOemDomainSupplied;
- domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
- ());
- }
- else
- {
- flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
- }
- byte[] workstation = new byte[0];
- if (!string.IsNullOrEmpty(suppliedWorkstation))
- {
- hostInfo = true;
- flags |= NtlmsspNegotiateOemWorkstationSupplied;
- workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
- ());
- }
- else
- {
- flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff
- )));
- }
- byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16
- ];
- Array.Copy(NtlmsspSignature, 0, type1, 0, 8);
- WriteULong(type1, 8, 1);
- WriteULong(type1, 12, flags);
- if (hostInfo)
- {
- WriteSecurityBuffer(type1, 16, 32, domain);
- WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
- }
- return type1;
- }
- catch (IOException ex)
- {
- throw new InvalidOperationException(ex.Message);
- }
- }
-
- public override string ToString()
- {
- string suppliedDomain = GetSuppliedDomain();
- string suppliedWorkstation = GetSuppliedWorkstation();
- return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
- ) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
- ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
- }
-
- /// <summary>
- /// Returns the default flags for a generic Type-1 message in the
- /// current environment.
- /// </summary>
- /// <remarks>
- /// Returns the default flags for a generic Type-1 message in the
- /// current environment.
- /// </remarks>
- /// <returns>An <code>int</code> containing the default flags.</returns>
- public static int GetDefaultFlags()
- {
- return DefaultFlags;
- }
-
- /// <summary>Returns the default domain from the current environment.</summary>
- /// <remarks>Returns the default domain from the current environment.</remarks>
- /// <returns>A <code>String</code> containing the default domain.</returns>
- public static string GetDefaultDomain()
- {
- return DefaultDomain;
- }
-
- /// <summary>Returns the default workstation from the current environment.</summary>
- /// <remarks>Returns the default workstation from the current environment.</remarks>
- /// <returns>A <code>String</code> containing the default workstation.</returns>
- public static string GetDefaultWorkstation()
- {
- return DefaultWorkstation;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- private void Parse(byte[] material)
- {
- for (int i = 0; i < 8; i++)
- {
- if (material[i] != NtlmsspSignature[i])
- {
- throw new IOException("Not an NTLMSSP message.");
- }
- }
- if (ReadULong(material, 8) != 1)
- {
- throw new IOException("Not a Type 1 message.");
- }
- int flags = ReadULong(material, 12);
- string suppliedDomain = null;
- if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
- {
- byte[] domain = ReadSecurityBuffer(material, 16);
- suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
- }
- string suppliedWorkstation = null;
- if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
- {
- byte[] workstation = ReadSecurityBuffer(material, 24);
- suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
- ());
- }
- SetFlags(flags);
- SetSuppliedDomain(suppliedDomain);
- SetSuppliedWorkstation(suppliedWorkstation);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs
deleted file mode 100644
index 104e5b0fd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs
+++ /dev/null
@@ -1,438 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Netbios;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Ntlmssp
-{
- /// <summary>Represents an NTLMSSP Type-2 message.</summary>
- /// <remarks>Represents an NTLMSSP Type-2 message.</remarks>
- public class Type2Message : NtlmMessage
- {
- private static readonly int DefaultFlags;
-
- private static readonly string DefaultDomain;
-
- private static readonly byte[] DefaultTargetInformation;
-
- private byte[] _challenge;
-
- private string _target;
-
- private byte[] _context;
-
- private byte[] _targetInformation;
-
- static Type2Message()
- {
- DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
- , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
- DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
- byte[] domain = new byte[0];
- if (DefaultDomain != null)
- {
- try
- {
- domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding);
- }
- catch (IOException)
- {
- }
- }
- int domainLength = domain.Length;
- byte[] server = new byte[0];
- try
- {
- string host = NbtAddress.GetLocalHost().GetHostName();
- if (host != null)
- {
- try
- {
- server = Runtime.GetBytesForString(host, UniEncoding);
- }
- catch (IOException)
- {
- }
- }
- }
- catch (UnknownHostException)
- {
- }
- int serverLength = server.Length;
- byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength
- > 0 ? serverLength + 4 : 0) + 4];
- int offset = 0;
- if (domainLength > 0)
- {
- WriteUShort(targetInfo, offset, 2);
- offset += 2;
- WriteUShort(targetInfo, offset, domainLength);
- offset += 2;
- Array.Copy(domain, 0, targetInfo, offset, domainLength);
- offset += domainLength;
- }
- if (serverLength > 0)
- {
- WriteUShort(targetInfo, offset, 1);
- offset += 2;
- WriteUShort(targetInfo, offset, serverLength);
- offset += 2;
- Array.Copy(server, 0, targetInfo, offset, serverLength);
- }
- DefaultTargetInformation = targetInfo;
- }
-
- /// <summary>
- /// Creates a Type-2 message using default values from the current
- /// environment.
- /// </summary>
- /// <remarks>
- /// Creates a Type-2 message using default values from the current
- /// environment.
- /// </remarks>
- public Type2Message() : this(GetDefaultFlags(), null, null)
- {
- }
-
- /// <summary>
- /// Creates a Type-2 message in response to the given Type-1 message
- /// using default values from the current environment.
- /// </summary>
- /// <remarks>
- /// Creates a Type-2 message in response to the given Type-1 message
- /// using default values from the current environment.
- /// </remarks>
- /// <param name="type1">The Type-1 message which this represents a response to.</param>
- public Type2Message(Type1Message type1) : this(type1, null, null)
- {
- }
-
- /// <summary>Creates a Type-2 message in response to the given Type-1 message.</summary>
- /// <remarks>Creates a Type-2 message in response to the given Type-1 message.</remarks>
- /// <param name="type1">The Type-1 message which this represents a response to.</param>
- /// <param name="challenge">The challenge from the domain controller/server.</param>
- /// <param name="target">The authentication target.</param>
- public Type2Message(Type1Message type1, byte[] challenge, string target) : this(GetDefaultFlags
- (type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget
- )) ? GetDefaultDomain() : target)
- {
- }
-
- /// <summary>Creates a Type-2 message with the specified parameters.</summary>
- /// <remarks>Creates a Type-2 message with the specified parameters.</remarks>
- /// <param name="flags">The flags to apply to this message.</param>
- /// <param name="challenge">The challenge from the domain controller/server.</param>
- /// <param name="target">The authentication target.</param>
- public Type2Message(int flags, byte[] challenge, string target)
- {
- SetFlags(flags);
- SetChallenge(challenge);
- SetTarget(target);
- if (target != null)
- {
- SetTargetInformation(GetDefaultTargetInformation());
- }
- }
-
- /// <summary>Creates a Type-2 message using the given raw Type-2 material.</summary>
- /// <remarks>Creates a Type-2 message using the given raw Type-2 material.</remarks>
- /// <param name="material">The raw Type-2 material used to construct this message.</param>
- /// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
- /// </exception>
- public Type2Message(byte[] material)
- {
- Parse(material);
- }
-
- /// <summary>Returns the challenge for this message.</summary>
- /// <remarks>Returns the challenge for this message.</remarks>
- /// <returns>A <code>byte[]</code> containing the challenge.</returns>
- public virtual byte[] GetChallenge()
- {
- return _challenge;
- }
-
- /// <summary>Sets the challenge for this message.</summary>
- /// <remarks>Sets the challenge for this message.</remarks>
- /// <param name="challenge">The challenge from the domain controller/server.</param>
- public virtual void SetChallenge(byte[] challenge)
- {
- this._challenge = challenge;
- }
-
- /// <summary>Returns the authentication target.</summary>
- /// <remarks>Returns the authentication target.</remarks>
- /// <returns>A <code>String</code> containing the authentication target.</returns>
- public virtual string GetTarget()
- {
- return _target;
- }
-
- /// <summary>Sets the authentication target.</summary>
- /// <remarks>Sets the authentication target.</remarks>
- /// <param name="target">The authentication target.</param>
- public virtual void SetTarget(string target)
- {
- this._target = target;
- }
-
- /// <summary>Returns the target information block.</summary>
- /// <remarks>Returns the target information block.</remarks>
- /// <returns>
- /// A <code>byte[]</code> containing the target information block.
- /// The target information block is used by the client to create an
- /// NTLMv2 response.
- /// </returns>
- public virtual byte[] GetTargetInformation()
- {
- return _targetInformation;
- }
-
- /// <summary>Sets the target information block.</summary>
- /// <remarks>
- /// Sets the target information block.
- /// The target information block is used by the client to create
- /// an NTLMv2 response.
- /// </remarks>
- /// <param name="targetInformation">The target information block.</param>
- public virtual void SetTargetInformation(byte[] targetInformation)
- {
- this._targetInformation = targetInformation;
- }
-
- /// <summary>Returns the local security context.</summary>
- /// <remarks>Returns the local security context.</remarks>
- /// <returns>
- /// A <code>byte[]</code> containing the local security
- /// context. This is used by the client to negotiate local
- /// authentication.
- /// </returns>
- public virtual byte[] GetContext()
- {
- return _context;
- }
-
- /// <summary>Sets the local security context.</summary>
- /// <remarks>
- /// Sets the local security context. This is used by the client
- /// to negotiate local authentication.
- /// </remarks>
- /// <param name="context">The local security context.</param>
- public virtual void SetContext(byte[] context)
- {
- this._context = context;
- }
-
- public override byte[] ToByteArray()
- {
- try
- {
- string targetName = GetTarget();
- byte[] challenge = GetChallenge();
- byte[] context = GetContext();
- byte[] targetInformation = GetTargetInformation();
- int flags = GetFlags();
- byte[] target = new byte[0];
- if ((flags & NtlmsspRequestTarget) != 0)
- {
- if (!string.IsNullOrEmpty(targetName))
- {
- target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString
- (targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper
- (), GetOemEncoding());
- }
- else
- {
- flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget);
- }
- }
- if (targetInformation != null)
- {
- flags |= NtlmsspNegotiateTargetInfo;
- // empty context is needed for padding when t.i. is supplied.
- if (context == null)
- {
- context = new byte[8];
- }
- }
- int data = 32;
- if (context != null)
- {
- data += 8;
- }
- if (targetInformation != null)
- {
- data += 8;
- }
- byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation
- .Length : 0)];
- Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
- WriteULong(type2, 8, 2);
- WriteSecurityBuffer(type2, 12, data, target);
- WriteULong(type2, 20, flags);
- Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8);
- if (context != null)
- {
- Array.Copy(context, 0, type2, 32, 8);
- }
- if (targetInformation != null)
- {
- WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation);
- }
- return type2;
- }
- catch (IOException ex)
- {
- throw new InvalidOperationException(ex.Message);
- }
- }
-
- public override string ToString()
- {
- string target = GetTarget();
- byte[] challenge = GetChallenge();
- byte[] context = GetContext();
- byte[] targetInformation = GetTargetInformation();
- return "Type2Message[target=" + target + ",challenge=" + (challenge == null ? "null"
- : "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null"
- : "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation
- == null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" +
- Hexdump.ToHexString(GetFlags(), 8) + "]";
- }
-
- /// <summary>
- /// Returns the default flags for a generic Type-2 message in the
- /// current environment.
- /// </summary>
- /// <remarks>
- /// Returns the default flags for a generic Type-2 message in the
- /// current environment.
- /// </remarks>
- /// <returns>An <code>int</code> containing the default flags.</returns>
- public static int GetDefaultFlags()
- {
- return DefaultFlags;
- }
-
- /// <summary>
- /// Returns the default flags for a Type-2 message created in response
- /// to the given Type-1 message in the current environment.
- /// </summary>
- /// <remarks>
- /// Returns the default flags for a Type-2 message created in response
- /// to the given Type-1 message in the current environment.
- /// </remarks>
- /// <returns>An <code>int</code> containing the default flags.</returns>
- public static int GetDefaultFlags(Type1Message type1)
- {
- if (type1 == null)
- {
- return DefaultFlags;
- }
- int flags = NtlmsspNegotiateNtlm;
- int type1Flags = type1.GetFlags();
- flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
- : NtlmsspNegotiateOem;
- if ((type1Flags & NtlmsspRequestTarget) != 0)
- {
- string domain = GetDefaultDomain();
- if (domain != null)
- {
- flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain;
- }
- }
- return flags;
- }
-
- /// <summary>Returns the default domain from the current environment.</summary>
- /// <remarks>Returns the default domain from the current environment.</remarks>
- /// <returns>A <code>String</code> containing the domain.</returns>
- public static string GetDefaultDomain()
- {
- return DefaultDomain;
- }
-
- public static byte[] GetDefaultTargetInformation()
- {
- return DefaultTargetInformation;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- private void Parse(byte[] material)
- {
- for (int i = 0; i < 8; i++)
- {
- if (material[i] != NtlmsspSignature[i])
- {
- throw new IOException("Not an NTLMSSP message.");
- }
- }
- if (ReadULong(material, 8) != 2)
- {
- throw new IOException("Not a Type 2 message.");
- }
- int flags = ReadULong(material, 20);
- SetFlags(flags);
- string target = null;
- byte[] bytes = ReadSecurityBuffer(material, 12);
- if (bytes.Length != 0)
- {
- target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode
- ) != 0) ? UniEncoding : GetOemEncoding());
- }
- SetTarget(target);
- for (int i1 = 24; i1 < 32; i1++)
- {
- if (material[i1] != 0)
- {
- byte[] challenge = new byte[8];
- Array.Copy(material, 24, challenge, 0, 8);
- SetChallenge(challenge);
- break;
- }
- }
- int offset = ReadULong(material, 16);
- // offset of targetname start
- if (offset == 32 || material.Length == 32)
- {
- return;
- }
- for (int i2 = 32; i2 < 40; i2++)
- {
- if (material[i2] != 0)
- {
- byte[] context = new byte[8];
- Array.Copy(material, 32, context, 0, 8);
- SetContext(context);
- break;
- }
- }
- if (offset == 40 || material.Length == 40)
- {
- return;
- }
- bytes = ReadSecurityBuffer(material, 40);
- if (bytes.Length != 0)
- {
- SetTargetInformation(bytes);
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs
deleted file mode 100644
index 9a2a37f3c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs
+++ /dev/null
@@ -1,677 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Netbios;
-using SharpCifs.Smb;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Ntlmssp
-{
- /// <summary>Represents an NTLMSSP Type-3 message.</summary>
- /// <remarks>Represents an NTLMSSP Type-3 message.</remarks>
- public class Type3Message : NtlmMessage
- {
- internal const long MillisecondsBetween1970And1601 = 11644473600000L;
-
- private static readonly int DefaultFlags;
-
- private static readonly string DefaultDomain;
-
- private static readonly string DefaultUser;
-
- private static readonly string DefaultPassword;
-
- private static readonly string DefaultWorkstation;
-
- private static readonly int LmCompatibility;
-
- //private static readonly SecureRandom RANDOM = new SecureRandom();
-
- private byte[] _lmResponse;
-
- private byte[] _ntResponse;
-
- private string _domain;
-
- private string _user;
-
- private string _workstation;
-
- private byte[] _masterKey;
-
- private byte[] _sessionKey;
-
- static Type3Message()
- {
- DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
- , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
- DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
- DefaultUser = Config.GetProperty("jcifs.smb.client.username", null);
- DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null);
- string defaultWorkstation = null;
- try
- {
- defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
- }
- catch (UnknownHostException)
- {
- }
- DefaultWorkstation = defaultWorkstation;
- LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
- }
-
- /// <summary>
- /// Creates a Type-3 message using default values from the current
- /// environment.
- /// </summary>
- /// <remarks>
- /// Creates a Type-3 message using default values from the current
- /// environment.
- /// </remarks>
- public Type3Message()
- {
- SetFlags(GetDefaultFlags());
- SetDomain(GetDefaultDomain());
- SetUser(GetDefaultUser());
- SetWorkstation(GetDefaultWorkstation());
- }
-
- /// <summary>
- /// Creates a Type-3 message in response to the given Type-2 message
- /// using default values from the current environment.
- /// </summary>
- /// <remarks>
- /// Creates a Type-3 message in response to the given Type-2 message
- /// using default values from the current environment.
- /// </remarks>
- /// <param name="type2">The Type-2 message which this represents a response to.</param>
- public Type3Message(Type2Message type2)
- {
- SetFlags(GetDefaultFlags(type2));
- SetWorkstation(GetDefaultWorkstation());
- string domain = GetDefaultDomain();
- SetDomain(domain);
- string user = GetDefaultUser();
- SetUser(user);
- string password = GetDefaultPassword();
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- {
- SetLmResponse(GetLMResponse(type2, password));
- SetNtResponse(GetNTResponse(type2, password));
- break;
- }
-
- case 2:
- {
- byte[] nt = GetNTResponse(type2, password);
- SetLmResponse(nt);
- SetNtResponse(nt);
- break;
- }
-
- case 3:
- case 4:
- case 5:
- {
- byte[] clientChallenge = new byte[8];
- //RANDOM.NextBytes(clientChallenge);
- SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge));
- break;
- }
-
- default:
- {
- SetLmResponse(GetLMResponse(type2, password));
- SetNtResponse(GetNTResponse(type2, password));
- break;
- }
- }
- }
-
- /// <summary>Creates a Type-3 message in response to the given Type-2 message.</summary>
- /// <remarks>Creates a Type-3 message in response to the given Type-2 message.</remarks>
- /// <param name="type2">The Type-2 message which this represents a response to.</param>
- /// <param name="password">The password to use when constructing the response.</param>
- /// <param name="domain">The domain in which the user has an account.</param>
- /// <param name="user">The username for the authenticating user.</param>
- /// <param name="workstation">
- /// The workstation from which authentication is
- /// taking place.
- /// </param>
- public Type3Message(Type2Message type2, string password, string domain, string user
- , string workstation, int flags)
- {
- SetFlags(flags | GetDefaultFlags(type2));
- if (workstation == null)
- {
- workstation = GetDefaultWorkstation();
- }
- SetWorkstation(workstation);
- SetDomain(domain);
- SetUser(user);
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- {
- if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0)
- {
- SetLmResponse(GetLMResponse(type2, password));
- SetNtResponse(GetNTResponse(type2, password));
- }
- else
- {
- // NTLM2 Session Response
- byte[] clientChallenge = new byte[24];
- //RANDOM.NextBytes(clientChallenge);
- Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00)));
- // NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient
- byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password);
- byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
- type2.GetChallenge(), clientChallenge);
- SetLmResponse(clientChallenge);
- SetNtResponse(ntlm2Response);
- if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
- {
- byte[] sessionNonce = new byte[16];
- Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8);
- Array.Copy(clientChallenge, 0, sessionNonce, 8, 8);
- Md4 md4 = new Md4();
- md4.Update(responseKeyNt);
- byte[] userSessionKey = md4.Digest();
- Hmact64 hmac = new Hmact64(userSessionKey);
- hmac.Update(sessionNonce);
- byte[] ntlm2SessionKey = hmac.Digest();
- if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
- {
- _masterKey = new byte[16];
- //RANDOM.NextBytes(masterKey);
- byte[] exchangedKey = new byte[16];
- Rc4 rc4 = new Rc4(ntlm2SessionKey);
- rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
- SetSessionKey(exchangedKey);
- }
- else
- {
- _masterKey = ntlm2SessionKey;
- SetSessionKey(_masterKey);
- }
- }
- }
- break;
- }
-
- case 2:
- {
- byte[] nt = GetNTResponse(type2, password);
- SetLmResponse(nt);
- SetNtResponse(nt);
- break;
- }
-
- case 3:
- case 4:
- case 5:
- {
- byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password
- );
- byte[] clientChallenge1 = new byte[8];
- //RANDOM.NextBytes(clientChallenge_1);
- SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1));
- byte[] clientChallenge2 = new byte[8];
- //RANDOM.NextBytes(clientChallenge2);
- SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2));
- if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
- {
- Hmact64 hmac = new Hmact64(responseKeyNt1);
- hmac.Update(_ntResponse, 0, 16);
- // only first 16 bytes of ntResponse
- byte[] userSessionKey = hmac.Digest();
- if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
- {
- _masterKey = new byte[16];
- //RANDOM.NextBytes(masterKey);
- byte[] exchangedKey = new byte[16];
- Rc4 rc4 = new Rc4(userSessionKey);
- rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
- SetSessionKey(exchangedKey);
- }
- else
- {
- _masterKey = userSessionKey;
- SetSessionKey(_masterKey);
- }
- }
- break;
- }
-
- default:
- {
- SetLmResponse(GetLMResponse(type2, password));
- SetNtResponse(GetNTResponse(type2, password));
- break;
- }
- }
- }
-
- /// <summary>Creates a Type-3 message with the specified parameters.</summary>
- /// <remarks>Creates a Type-3 message with the specified parameters.</remarks>
- /// <param name="flags">The flags to apply to this message.</param>
- /// <param name="lmResponse">The LanManager/LMv2 response.</param>
- /// <param name="ntResponse">The NT/NTLMv2 response.</param>
- /// <param name="domain">The domain in which the user has an account.</param>
- /// <param name="user">The username for the authenticating user.</param>
- /// <param name="workstation">
- /// The workstation from which authentication is
- /// taking place.
- /// </param>
- public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse, string domain
- , string user, string workstation)
- {
- SetFlags(flags);
- SetLmResponse(lmResponse);
- SetNtResponse(ntResponse);
- SetDomain(domain);
- SetUser(user);
- SetWorkstation(workstation);
- }
-
- /// <summary>Creates a Type-3 message using the given raw Type-3 material.</summary>
- /// <remarks>Creates a Type-3 message using the given raw Type-3 material.</remarks>
- /// <param name="material">The raw Type-3 material used to construct this message.</param>
- /// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
- /// </exception>
- public Type3Message(byte[] material)
- {
- Parse(material);
- }
-
- /// <summary>Returns the LanManager/LMv2 response.</summary>
- /// <remarks>Returns the LanManager/LMv2 response.</remarks>
- /// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
- public virtual byte[] GetLMResponse()
- {
- return _lmResponse;
- }
-
- /// <summary>Sets the LanManager/LMv2 response for this message.</summary>
- /// <remarks>Sets the LanManager/LMv2 response for this message.</remarks>
- /// <param name="lmResponse">The LanManager response.</param>
- public virtual void SetLmResponse(byte[] lmResponse)
- {
- this._lmResponse = lmResponse;
- }
-
- /// <summary>Returns the NT/NTLMv2 response.</summary>
- /// <remarks>Returns the NT/NTLMv2 response.</remarks>
- /// <returns>A <code>byte[]</code> containing the NT/NTLMv2 response.</returns>
- public virtual byte[] GetNTResponse()
- {
- return _ntResponse;
- }
-
- /// <summary>Sets the NT/NTLMv2 response for this message.</summary>
- /// <remarks>Sets the NT/NTLMv2 response for this message.</remarks>
- /// <param name="ntResponse">The NT/NTLMv2 response.</param>
- public virtual void SetNtResponse(byte[] ntResponse)
- {
- this._ntResponse = ntResponse;
- }
-
- /// <summary>Returns the domain in which the user has an account.</summary>
- /// <remarks>Returns the domain in which the user has an account.</remarks>
- /// <returns>A <code>String</code> containing the domain for the user.</returns>
- public virtual string GetDomain()
- {
- return _domain;
- }
-
- /// <summary>Sets the domain for this message.</summary>
- /// <remarks>Sets the domain for this message.</remarks>
- /// <param name="domain">The domain.</param>
- public virtual void SetDomain(string domain)
- {
- this._domain = domain;
- }
-
- /// <summary>Returns the username for the authenticating user.</summary>
- /// <remarks>Returns the username for the authenticating user.</remarks>
- /// <returns>A <code>String</code> containing the user for this message.</returns>
- public virtual string GetUser()
- {
- return _user;
- }
-
- /// <summary>Sets the user for this message.</summary>
- /// <remarks>Sets the user for this message.</remarks>
- /// <param name="user">The user.</param>
- public virtual void SetUser(string user)
- {
- this._user = user;
- }
-
- /// <summary>Returns the workstation from which authentication is being performed.</summary>
- /// <remarks>Returns the workstation from which authentication is being performed.</remarks>
- /// <returns>A <code>String</code> containing the workstation.</returns>
- public virtual string GetWorkstation()
- {
- return _workstation;
- }
-
- /// <summary>Sets the workstation for this message.</summary>
- /// <remarks>Sets the workstation for this message.</remarks>
- /// <param name="workstation">The workstation.</param>
- public virtual void SetWorkstation(string workstation)
- {
- this._workstation = workstation;
- }
-
- /// <summary>
- /// The real session key if the regular session key is actually
- /// the encrypted version used for key exchange.
- /// </summary>
- /// <remarks>
- /// The real session key if the regular session key is actually
- /// the encrypted version used for key exchange.
- /// </remarks>
- /// <returns>A <code>byte[]</code> containing the session key.</returns>
- public virtual byte[] GetMasterKey()
- {
- return _masterKey;
- }
-
- /// <summary>Returns the session key.</summary>
- /// <remarks>Returns the session key.</remarks>
- /// <returns>A <code>byte[]</code> containing the session key.</returns>
- public virtual byte[] GetSessionKey()
- {
- return _sessionKey;
- }
-
- /// <summary>Sets the session key.</summary>
- /// <remarks>Sets the session key.</remarks>
- /// <param name="sessionKey">The session key.</param>
- public virtual void SetSessionKey(byte[] sessionKey)
- {
- this._sessionKey = sessionKey;
- }
-
- public override byte[] ToByteArray()
- {
- try
- {
- int flags = GetFlags();
- bool unicode = (flags & NtlmsspNegotiateUnicode) != 0;
- string oem = unicode ? null : GetOemEncoding();
- string domainName = GetDomain();
- byte[] domain = null;
- if (!string.IsNullOrEmpty(domainName))
- {
- domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) :
- Runtime.GetBytesForString(domainName, oem);
- }
- int domainLength = (domain != null) ? domain.Length : 0;
- string userName = GetUser();
- byte[] user = null;
- if (!string.IsNullOrEmpty(userName))
- {
- user = unicode ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString
- (userName.ToUpper(), oem);
- }
- int userLength = (user != null) ? user.Length : 0;
- string workstationName = GetWorkstation();
- byte[] workstation = null;
- if (!string.IsNullOrEmpty(workstationName))
- {
- workstation = unicode ? Runtime.GetBytesForString(workstationName, UniEncoding
- ) : Runtime.GetBytesForString(workstationName.ToUpper(), oem);
- }
- int workstationLength = (workstation != null) ? workstation.Length : 0;
- byte[] lmResponse = GetLMResponse();
- int lmLength = (lmResponse != null) ? lmResponse.Length : 0;
- byte[] ntResponse = GetNTResponse();
- int ntLength = (ntResponse != null) ? ntResponse.Length : 0;
- byte[] sessionKey = GetSessionKey();
- int keyLength = (sessionKey != null) ? sessionKey.Length : 0;
- byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength
- + ntLength + keyLength];
- Array.Copy(NtlmsspSignature, 0, type3, 0, 8);
- WriteULong(type3, 8, 3);
- int offset = 64;
- WriteSecurityBuffer(type3, 12, offset, lmResponse);
- offset += lmLength;
- WriteSecurityBuffer(type3, 20, offset, ntResponse);
- offset += ntLength;
- WriteSecurityBuffer(type3, 28, offset, domain);
- offset += domainLength;
- WriteSecurityBuffer(type3, 36, offset, user);
- offset += userLength;
- WriteSecurityBuffer(type3, 44, offset, workstation);
- offset += workstationLength;
- WriteSecurityBuffer(type3, 52, offset, sessionKey);
- WriteULong(type3, 60, flags);
- return type3;
- }
- catch (IOException ex)
- {
- throw new InvalidOperationException(ex.Message);
- }
- }
-
- public override string ToString()
- {
- string user = GetUser();
- string domain = GetDomain();
- string workstation = GetWorkstation();
- byte[] lmResponse = GetLMResponse();
- byte[] ntResponse = GetNTResponse();
- byte[] sessionKey = GetSessionKey();
- return "Type3Message[domain=" + domain + ",user=" + user + ",workstation=" + workstation
- + ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>"
- ) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>"
- ) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>"
- ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
- }
-
- /// <summary>
- /// Returns the default flags for a generic Type-3 message in the
- /// current environment.
- /// </summary>
- /// <remarks>
- /// Returns the default flags for a generic Type-3 message in the
- /// current environment.
- /// </remarks>
- /// <returns>An <code>int</code> containing the default flags.</returns>
- public static int GetDefaultFlags()
- {
- return DefaultFlags;
- }
-
- /// <summary>
- /// Returns the default flags for a Type-3 message created in response
- /// to the given Type-2 message in the current environment.
- /// </summary>
- /// <remarks>
- /// Returns the default flags for a Type-3 message created in response
- /// to the given Type-2 message in the current environment.
- /// </remarks>
- /// <returns>An <code>int</code> containing the default flags.</returns>
- public static int GetDefaultFlags(Type2Message type2)
- {
- if (type2 == null)
- {
- return DefaultFlags;
- }
- int flags = NtlmsspNegotiateNtlm;
- flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
- : NtlmsspNegotiateOem;
- return flags;
- }
-
- /// <summary>
- /// Constructs the LanManager response to the given Type-2 message using
- /// the supplied password.
- /// </summary>
- /// <remarks>
- /// Constructs the LanManager response to the given Type-2 message using
- /// the supplied password.
- /// </remarks>
- /// <param name="type2">The Type-2 message.</param>
- /// <param name="password">The password.</param>
- /// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
- public static byte[] GetLMResponse(Type2Message type2, string password)
- {
- if (type2 == null || password == null)
- {
- return null;
- }
- return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge
- ());
- }
-
- public static byte[] GetLMv2Response(Type2Message type2, string domain, string user
- , string password, byte[] clientChallenge)
- {
- if (type2 == null || domain == null || user == null || password == null || clientChallenge
- == null)
- {
- return null;
- }
- return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge
- (), clientChallenge);
- }
-
- public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt,
- byte[] clientChallenge)
- {
- if (type2 == null || responseKeyNt == null || clientChallenge == null)
- {
- return null;
- }
- long nanos1601 = (Runtime.CurrentTimeMillis() + MillisecondsBetween1970And1601
- ) * 10000L;
- return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge
- (), clientChallenge, nanos1601, type2.GetTargetInformation());
- }
-
- /// <summary>
- /// Constructs the NT response to the given Type-2 message using
- /// the supplied password.
- /// </summary>
- /// <remarks>
- /// Constructs the NT response to the given Type-2 message using
- /// the supplied password.
- /// </remarks>
- /// <param name="type2">The Type-2 message.</param>
- /// <param name="password">The password.</param>
- /// <returns>A <code>byte[]</code> containing the NT response.</returns>
- public static byte[] GetNTResponse(Type2Message type2, string password)
- {
- if (type2 == null || password == null)
- {
- return null;
- }
- return NtlmPasswordAuthentication.GetNtlmResponse(password, type2.GetChallenge());
- }
-
- /// <summary>Returns the default domain from the current environment.</summary>
- /// <remarks>Returns the default domain from the current environment.</remarks>
- /// <returns>The default domain.</returns>
- public static string GetDefaultDomain()
- {
- return DefaultDomain;
- }
-
- /// <summary>Returns the default user from the current environment.</summary>
- /// <remarks>Returns the default user from the current environment.</remarks>
- /// <returns>The default user.</returns>
- public static string GetDefaultUser()
- {
- return DefaultUser;
- }
-
- /// <summary>Returns the default password from the current environment.</summary>
- /// <remarks>Returns the default password from the current environment.</remarks>
- /// <returns>The default password.</returns>
- public static string GetDefaultPassword()
- {
- return DefaultPassword;
- }
-
- /// <summary>Returns the default workstation from the current environment.</summary>
- /// <remarks>Returns the default workstation from the current environment.</remarks>
- /// <returns>The default workstation.</returns>
- public static string GetDefaultWorkstation()
- {
- return DefaultWorkstation;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- private void Parse(byte[] material)
- {
- for (int i = 0; i < 8; i++)
- {
- if (material[i] != NtlmsspSignature[i])
- {
- throw new IOException("Not an NTLMSSP message.");
- }
- }
- if (ReadULong(material, 8) != 3)
- {
- throw new IOException("Not a Type 3 message.");
- }
- byte[] lmResponse = ReadSecurityBuffer(material, 12);
- int lmResponseOffset = ReadULong(material, 16);
- byte[] ntResponse = ReadSecurityBuffer(material, 20);
- int ntResponseOffset = ReadULong(material, 24);
- byte[] domain = ReadSecurityBuffer(material, 28);
- int domainOffset = ReadULong(material, 32);
- byte[] user = ReadSecurityBuffer(material, 36);
- int userOffset = ReadULong(material, 40);
- byte[] workstation = ReadSecurityBuffer(material, 44);
- int workstationOffset = ReadULong(material, 48);
- int flags;
- string charset;
- byte[] _sessionKey = null;
- if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset
- == 52 || workstationOffset == 52)
- {
- flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem;
- charset = GetOemEncoding();
- }
- else
- {
- _sessionKey = ReadSecurityBuffer(material, 52);
- flags = ReadULong(material, 60);
- charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding
- ();
- }
- SetSessionKey(_sessionKey);
- SetFlags(flags);
- SetLmResponse(lmResponse);
- SetNtResponse(ntResponse);
- SetDomain(Runtime.GetStringForBytes(domain, charset));
- SetUser(Runtime.GetStringForBytes(user, charset));
- SetWorkstation(Runtime.GetStringForBytes(workstation, charset));
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs
deleted file mode 100644
index 73b742cfb..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs
+++ /dev/null
@@ -1,287 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.Text;
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- /// <summary>
- /// An Access Control Entry (ACE) is an element in a security descriptor
- /// such as those associated with files and directories.
- /// </summary>
- /// <remarks>
- /// An Access Control Entry (ACE) is an element in a security descriptor
- /// such as those associated with files and directories. The Windows OS
- /// determines which users have the necessary permissions to access objects
- /// based on these entries.
- /// <p>
- /// To fully understand the information exposed by this class a description
- /// of the access check algorithm used by Windows is required. The following
- /// is a basic description of the algorithm. For a more complete description
- /// we recommend reading the section on Access Control in Keith Brown's
- /// "The .NET Developer's Guide to Windows Security" (which is also
- /// available online).
- /// <p>
- /// Direct ACEs are evaluated first in order. The SID of the user performing
- /// the operation and the desired access bits are compared to the SID
- /// and access mask of each ACE. If the SID matches, the allow/deny flags
- /// and access mask are considered. If the ACE is a "deny"
- /// ACE and <i>any</i> of the desired access bits match bits in the access
- /// mask of the ACE, the whole access check fails. If the ACE is an "allow"
- /// ACE and <i>all</i> of the bits in the desired access bits match bits in
- /// the access mask of the ACE, the access check is successful. Otherwise,
- /// more ACEs are evaluated until all desired access bits (combined)
- /// are "allowed". If all of the desired access bits are not "allowed"
- /// the then same process is repeated for inherited ACEs.
- /// <p>
- /// For example, if user <tt>WNET\alice</tt> tries to open a file
- /// with desired access bits <tt>0x00000003</tt> (<tt>FILE_READ_DATA |
- /// FILE_WRITE_DATA</tt>) and the target file has the following security
- /// descriptor ACEs:
- /// <pre>
- /// Allow WNET\alice 0x001200A9 Direct
- /// Allow Administrators 0x001F01FF Inherited
- /// Allow SYSTEM 0x001F01FF Inherited
- /// </pre>
- /// the access check would fail because the direct ACE has an access mask
- /// of <tt>0x001200A9</tt> which doesn't have the
- /// <tt>FILE_WRITE_DATA</tt> bit on (bit <tt>0x00000002</tt>). Actually, this isn't quite correct. If
- /// <tt>WNET\alice</tt> is in the local <tt>Administrators</tt> group the access check
- /// will succeed because the inherited ACE allows local <tt>Administrators</tt>
- /// both <tt>FILE_READ_DATA</tt> and <tt>FILE_WRITE_DATA</tt> access.
- /// </remarks>
- public class Ace
- {
- public const int FileReadData = unchecked(0x00000001);
-
- public const int FileWriteData = unchecked(0x00000002);
-
- public const int FileAppendData = unchecked(0x00000004);
-
- public const int FileReadEa = unchecked(0x00000008);
-
- public const int FileWriteEa = unchecked(0x00000010);
-
- public const int FileExecute = unchecked(0x00000020);
-
- public const int FileDelete = unchecked(0x00000040);
-
- public const int FileReadAttributes = unchecked(0x00000080);
-
- public const int FileWriteAttributes = unchecked(0x00000100);
-
- public const int Delete = unchecked(0x00010000);
-
- public const int ReadControl = unchecked(0x00020000);
-
- public const int WriteDac = unchecked(0x00040000);
-
- public const int WriteOwner = unchecked(0x00080000);
-
- public const int Synchronize = unchecked(0x00100000);
-
- public const int GenericAll = unchecked(0x10000000);
-
- public const int GenericExecute = unchecked(0x20000000);
-
- public const int GenericWrite = unchecked(0x40000000);
-
- public const int GenericRead = unchecked((int)(0x80000000));
-
- public const int FlagsObjectInherit = unchecked(0x01);
-
- public const int FlagsContainerInherit = unchecked(0x02);
-
- public const int FlagsNoPropagate = unchecked(0x04);
-
- public const int FlagsInheritOnly = unchecked(0x08);
-
- public const int FlagsInherited = unchecked(0x10);
-
- internal bool Allow;
-
- internal int Flags;
-
- internal int Access;
-
- internal Sid Sid;
-
- // 1
- // 2
- // 3
- // 4
- // 5
- // 6
- // 7
- // 8
- // 9
- // 16
- // 17
- // 18
- // 19
- // 20
- // 28
- // 29
- // 30
- // 31
- /// <summary>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</summary>
- /// <remarks>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</remarks>
- public virtual bool IsAllow()
- {
- return Allow;
- }
-
- /// <summary>Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
- /// </summary>
- /// <remarks>
- /// Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
- /// <p>
- /// Note: For reasons not fully understood, <tt>FLAGS_INHERITED</tt> may
- /// not be set within all security descriptors even though the ACE was in
- /// face inherited. If an inherited ACE is added to a parent the Windows
- /// ACL editor will rebuild all children ACEs and set this flag accordingly.
- /// </remarks>
- public virtual bool IsInherited()
- {
- return (Flags & FlagsInherited) != 0;
- }
-
- /// <summary>Returns the flags for this ACE.</summary>
- /// <remarks>
- /// Returns the flags for this ACE. The </tt>isInherited()</tt>
- /// method checks the <tt>FLAGS_INHERITED</tt> bit in these flags.
- /// </remarks>
- public virtual int GetFlags()
- {
- return Flags;
- }
-
- /// <summary>
- /// Returns the 'Apply To' text for inheritance of ACEs on
- /// directories such as 'This folder, subfolder and files'.
- /// </summary>
- /// <remarks>
- /// Returns the 'Apply To' text for inheritance of ACEs on
- /// directories such as 'This folder, subfolder and files'. For
- /// files the text is always 'This object only'.
- /// </remarks>
- public virtual string GetApplyToText()
- {
- switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly
- ))
- {
- case unchecked(0x00):
- {
- return "This folder only";
- }
-
- case unchecked(0x03):
- {
- return "This folder, subfolders and files";
- }
-
- case unchecked(0x0B):
- {
- return "Subfolders and files only";
- }
-
- case unchecked(0x02):
- {
- return "This folder and subfolders";
- }
-
- case unchecked(0x0A):
- {
- return "Subfolders only";
- }
-
- case unchecked(0x01):
- {
- return "This folder and files";
- }
-
- case unchecked(0x09):
- {
- return "Files only";
- }
- }
- return "Invalid";
- }
-
- /// <summary>Returns the access mask accociated with this ACE.</summary>
- /// <remarks>
- /// Returns the access mask accociated with this ACE. Use the
- /// constants for <tt>FILE_READ_DATA</tt>, <tt>FILE_WRITE_DATA</tt>,
- /// <tt>READ_CONTROL</tt>, <tt>GENERIC_ALL</tt>, etc with bitwise
- /// operators to determine which bits of the mask are on or off.
- /// </remarks>
- public virtual int GetAccessMask()
- {
- return Access;
- }
-
- /// <summary>Return the SID associated with this ACE.</summary>
- /// <remarks>Return the SID associated with this ACE.</remarks>
- public virtual Sid GetSid()
- {
- return Sid;
- }
-
- internal virtual int Decode(byte[] buf, int bi)
- {
- Allow = buf[bi++] == unchecked(unchecked(0x00));
- Flags = buf[bi++] & unchecked(0xFF);
- int size = ServerMessageBlock.ReadInt2(buf, bi);
- bi += 2;
- Access = ServerMessageBlock.ReadInt4(buf, bi);
- bi += 4;
- Sid = new Sid(buf, bi);
- return size;
- }
-
- internal virtual void AppendCol(StringBuilder sb, string str, int width)
- {
- sb.Append(str);
- int count = width - str.Length;
- for (int i = 0; i < count; i++)
- {
- sb.Append(' ');
- }
- }
-
- /// <summary>Return a string represeting this ACE.</summary>
- /// <remarks>
- /// Return a string represeting this ACE.
- /// <p>
- /// Note: This function should probably be changed to return SDDL
- /// fragments but currently it does not.
- /// </remarks>
- public override string ToString()
- {
- int count;
- int i;
- string str;
- StringBuilder sb = new StringBuilder();
- sb.Append(IsAllow() ? "Allow " : "Deny ");
- AppendCol(sb, Sid.ToDisplayString(), 25);
- sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
- sb.Append(IsInherited() ? "Inherited " : "Direct ");
- AppendCol(sb, GetApplyToText(), 34);
- return sb.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs
deleted file mode 100644
index 6ebe88293..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal interface IAllocInfo
- {
- long GetCapacity();
-
- long GetFree();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs
deleted file mode 100644
index e78bff9d0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs
+++ /dev/null
@@ -1,221 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal abstract class AndXServerMessageBlock : ServerMessageBlock
- {
- private const int AndxCommandOffset = 1;
-
- private const int AndxReservedOffset = 2;
-
- private const int AndxOffsetOffset = 3;
-
- private byte _andxCommand = unchecked(unchecked(0xFF));
-
- private int _andxOffset;
-
- internal ServerMessageBlock Andx;
-
- public AndXServerMessageBlock()
- {
- }
-
- internal AndXServerMessageBlock(ServerMessageBlock andx)
- {
- if (andx != null)
- {
- this.Andx = andx;
- _andxCommand = andx.Command;
- }
- }
-
- internal virtual int GetBatchLimit(byte command)
- {
- return 0;
- }
-
- internal override int Encode(byte[] dst, int dstIndex)
- {
- int start = HeaderStart = dstIndex;
- dstIndex += WriteHeaderWireFormat(dst, dstIndex);
- dstIndex += WriteAndXWireFormat(dst, dstIndex);
- Length = dstIndex - start;
- if (Digest != null)
- {
- Digest.Sign(dst, HeaderStart, Length, this, Response);
- }
- return Length;
- }
-
- internal override int Decode(byte[] buffer, int bufferIndex)
- {
- int start = HeaderStart = bufferIndex;
- bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
- bufferIndex += ReadAndXWireFormat(buffer, bufferIndex);
- Length = bufferIndex - start;
- return Length;
- }
-
- internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2);
- WordCount += 4;
- // for command, reserved, and offset
- dstIndex += WordCount + 1;
- WordCount /= 2;
- dst[start] = unchecked((byte)(WordCount & unchecked(0xFF)));
- ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
- dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF)));
- dstIndex += ByteCount;
- if (Andx == null || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command
- ))
- {
- _andxCommand = unchecked(unchecked(0xFF));
- Andx = null;
- dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF));
- dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
- // dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
- // dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
- dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde));
- dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde));
- // andx not used; return
- return dstIndex - start;
- }
- Andx.BatchLevel = BatchLevel + 1;
- dst[start + AndxCommandOffset] = _andxCommand;
- dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
- _andxOffset = dstIndex - HeaderStart;
- WriteInt2(_andxOffset, dst, start + AndxOffsetOffset);
- Andx.UseUnicode = UseUnicode;
- if (Andx is AndXServerMessageBlock)
- {
- Andx.Uid = Uid;
- dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex
- );
- }
- else
- {
- // the andx smb is not of type andx so lets just write it here and
- // were done.
- int andxStart = dstIndex;
- Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex);
- dstIndex += Andx.WordCount + 1;
- Andx.WordCount /= 2;
- dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)));
- Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2);
- dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF)));
- dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF)
- ));
- dstIndex += Andx.ByteCount;
- }
- return dstIndex - start;
- }
-
- internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex)
- {
- int start = bufferIndex;
- WordCount = buffer[bufferIndex++];
- if (WordCount != 0)
- {
- _andxCommand = buffer[bufferIndex];
- _andxOffset = ReadInt2(buffer, bufferIndex + 2);
- if (_andxOffset == 0)
- {
- _andxCommand = unchecked(unchecked(0xFF));
- }
- if (WordCount > 2)
- {
- ReadParameterWordsWireFormat(buffer, bufferIndex + 4);
- if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended)
- {
- WordCount += 8;
- }
- }
- bufferIndex = start + 1 + (WordCount * 2);
- }
- ByteCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if (ByteCount != 0)
- {
- int n;
- n = ReadBytesWireFormat(buffer, bufferIndex);
- bufferIndex += ByteCount;
- }
- if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF)))
- {
- _andxCommand = unchecked(unchecked(0xFF));
- Andx = null;
- }
- else
- {
- if (Andx == null)
- {
- _andxCommand = unchecked(unchecked(0xFF));
- throw new RuntimeException("no andx command supplied with response");
- }
- bufferIndex = HeaderStart + _andxOffset;
- Andx.HeaderStart = HeaderStart;
- Andx.Command = _andxCommand;
- Andx.ErrorCode = ErrorCode;
- Andx.Flags = Flags;
- Andx.Flags2 = Flags2;
- Andx.Tid = Tid;
- Andx.Pid = Pid;
- Andx.Uid = Uid;
- Andx.Mid = Mid;
- Andx.UseUnicode = UseUnicode;
- if (Andx is AndXServerMessageBlock)
- {
- bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer
- , bufferIndex);
- }
- else
- {
- buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))
- );
- if (Andx.WordCount != 0)
- {
- if (Andx.WordCount > 2)
- {
- bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex);
- }
- }
- Andx.ByteCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if (Andx.ByteCount != 0)
- {
- Andx.ReadBytesWireFormat(buffer, bufferIndex);
- bufferIndex += Andx.ByteCount;
- }
- }
- Andx.Received = true;
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand
- , 2) + ",andxOffset=" + _andxOffset;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs
deleted file mode 100644
index b36816e26..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public class BufferCache
- {
- private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16
- );
-
- internal static object[] Cache = new object[MaxBuffers];
-
- private static int _freeBuffers;
-
- public static byte[] GetBuffer()
- {
- lock (Cache)
- {
- byte[] buf;
- if (_freeBuffers > 0)
- {
- for (int i = 0; i < MaxBuffers; i++)
- {
- if (Cache[i] != null)
- {
- buf = (byte[])Cache[i];
- Cache[i] = null;
- _freeBuffers--;
- return buf;
- }
- }
- }
- buf = new byte[SmbComTransaction.TransactionBufSize];
- return buf;
- }
- }
-
- internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
- rsp)
- {
- lock (Cache)
- {
- req.TxnBuf = GetBuffer();
- rsp.TxnBuf = GetBuffer();
- }
- }
-
- public static void ReleaseBuffer(byte[] buf)
- {
- lock (Cache)
- {
- if (_freeBuffers < MaxBuffers)
- {
- for (int i = 0; i < MaxBuffers; i++)
- {
- if (Cache[i] == null)
- {
- Cache[i] = buf;
- _freeBuffers++;
- return;
- }
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs
deleted file mode 100644
index 2f62e5b8d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs
+++ /dev/null
@@ -1,389 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- public class Dfs
- {
- internal class CacheEntry
- {
- internal long Expiration;
-
- internal Hashtable Map;
-
- internal CacheEntry(long ttl)
- {
- if (ttl == 0)
- {
- ttl = Ttl;
- }
- Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L;
- Map = new Hashtable();
- }
- }
-
- internal static LogStream Log = LogStream.GetInstance();
-
- internal static readonly bool StrictView = Config.GetBoolean("jcifs.smb.client.dfs.strictView"
- , false);
-
- internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300
- );
-
- internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled"
- , false);
-
- internal static CacheEntry FalseEntry = new CacheEntry(0L);
-
- internal CacheEntry Domains;
-
- internal CacheEntry Referrals;
-
- /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
- public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth)
- {
- if (Disabled || auth.Domain == "?")
- {
- return null;
- }
- if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration)
- {
- Domains = null;
- }
- if (Domains != null)
- {
- return Domains.Map;
- }
- try
- {
- UniAddress addr = UniAddress.GetByName(auth.Domain, true);
- SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
- CacheEntry entry = new CacheEntry(Ttl * 10L);
- DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0);
- if (dr != null)
- {
- DfsReferral start = dr;
- do
- {
- string domain = dr.Server.ToLower();
- entry.Map.Put(domain, new Hashtable());
- dr = dr.Next;
- }
- while (dr != start);
- Domains = entry;
- return Domains.Map;
- }
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 3)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- if (StrictView && ioe is SmbAuthException)
- {
- throw (SmbAuthException)ioe;
- }
- }
- return null;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
- public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth
- )
- {
- Hashtable domains = GetTrustedDomains(auth);
- if (domains == null)
- {
- return false;
- }
- domain = domain.ToLower();
- return domains.Get(domain) != null;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
- public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth)
- {
- if (Disabled)
- {
- return null;
- }
- try
- {
- UniAddress addr = UniAddress.GetByName(domain, true);
- SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
- DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1);
- if (dr != null)
- {
- DfsReferral start = dr;
- IOException e = null;
- do
- {
- try
- {
- addr = UniAddress.GetByName(dr.Server);
- return SmbTransport.GetSmbTransport(addr, 0);
- }
- catch (IOException ioe)
- {
- e = ioe;
- }
- dr = dr.Next;
- }
- while (dr != start);
- throw e;
- }
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 3)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- if (StrictView && ioe is SmbAuthException)
- {
- throw (SmbAuthException)ioe;
- }
- }
- return null;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
- public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string
- root, string path, NtlmPasswordAuthentication auth)
- {
- if (Disabled)
- {
- return null;
- }
- try
- {
- string p = "\\" + domain + "\\" + root;
- if (path != null)
- {
- p += path;
- }
- DfsReferral dr = trans.GetDfsReferrals(auth, p, 0);
- if (dr != null)
- {
- return dr;
- }
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 4)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- if (StrictView && ioe is SmbAuthException)
- {
- throw (SmbAuthException)ioe;
- }
- }
- return null;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
- public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication
- auth)
- {
- lock (this)
- {
- DfsReferral dr = null;
- long now = Runtime.CurrentTimeMillis();
- if (Disabled || root.Equals("IPC$"))
- {
- return null;
- }
- Hashtable domains = GetTrustedDomains(auth);
- if (domains != null)
- {
- domain = domain.ToLower();
- Hashtable roots = (Hashtable)domains.Get(domain);
- if (roots != null)
- {
- SmbTransport trans = null;
- root = root.ToLower();
- CacheEntry links = (CacheEntry)roots.Get(root);
- if (links != null && now > links.Expiration)
- {
- //Sharpen.Collections.Remove(roots, root);
- roots.Remove(root);
- links = null;
- }
- if (links == null)
- {
- if ((trans = GetDc(domain, auth)) == null)
- {
- return null;
- }
- dr = GetReferral(trans, domain, root, path, auth);
- if (dr != null)
- {
- int len = 1 + domain.Length + 1 + root.Length;
- links = new CacheEntry(0L);
- DfsReferral tmp = dr;
- do
- {
- if (path == null)
- {
- // TODO: fix this
- //tmp.map = links.map;
- tmp.Key = "\\";
- }
- tmp.PathConsumed -= len;
- tmp = tmp.Next;
- }
- while (tmp != dr);
- if (dr.Key != null)
- {
- links.Map.Put(dr.Key, dr);
- }
- roots.Put(root, links);
- }
- else
- {
- if (path == null)
- {
- roots.Put(root, FalseEntry);
- }
- }
- }
- else
- {
- if (links == FalseEntry)
- {
- links = null;
- }
- }
- if (links != null)
- {
- string link = "\\";
- dr = (DfsReferral)links.Map.Get(link);
- if (dr != null && now > dr.Expiration)
- {
- //Sharpen.Collections.Remove(links.map, link);
- links.Map.Remove(link);
- dr = null;
- }
- if (dr == null)
- {
- if (trans == null)
- {
- if ((trans = GetDc(domain, auth)) == null)
- {
- return null;
- }
- }
- dr = GetReferral(trans, domain, root, path, auth);
- if (dr != null)
- {
- dr.PathConsumed -= 1 + domain.Length + 1 + root.Length;
- dr.Link = link;
- links.Map.Put(link, dr);
- }
- }
- }
- }
- }
- if (dr == null && path != null)
- {
- if (Referrals != null && now > Referrals.Expiration)
- {
- Referrals = null;
- }
- if (Referrals == null)
- {
- Referrals = new CacheEntry(0);
- }
- string key = "\\" + domain + "\\" + root;
- if (path.Equals("\\") == false)
- {
- key += path;
- }
- key = key.ToLower();
- //ListIterator<object> iter = new ListIterator<object>(referrals.map.Keys.GetEnumerator(), 0);
- foreach (var current in Referrals.Map.Keys)
- {
- string _key = (string)current;
- int klen = _key.Length;
- bool match = false;
- if (klen == key.Length)
- {
- match = _key.Equals(key);
- }
- else
- {
- if (klen < key.Length)
- {
- match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\';
- }
- }
- if (match)
- {
- dr = (DfsReferral)Referrals.Map.Get(_key);
- }
- }
- }
- return dr;
- }
- }
-
- internal virtual void Insert(string path, DfsReferral dr)
- {
- lock (this)
- {
- int s1;
- int s2;
- string server;
- string share;
- string key;
- if (Disabled)
- {
- return;
- }
- s1 = path.IndexOf('\\', 1);
- s2 = path.IndexOf('\\', s1 + 1);
- server = Runtime.Substring(path, 1, s1);
- share = Runtime.Substring(path, s1 + 1, s2);
- key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower();
- int ki = key.Length;
- while (ki > 1 && key[ki - 1] == '\\')
- {
- ki--;
- }
- if (ki < key.Length)
- {
- key = Runtime.Substring(key, 0, ki);
- }
- dr.PathConsumed -= 1 + server.Length + 1 + share.Length;
- if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration)
- {
- Referrals = null;
- }
- if (Referrals == null)
- {
- Referrals = new CacheEntry(0);
- }
- Referrals.Map.Put(key, dr);
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs
deleted file mode 100644
index 3b6091f73..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.Collections.Generic;
-
-namespace SharpCifs.Smb
-{
-
- public class DfsReferral : SmbException
- {
- public int PathConsumed;
-
- public long Ttl;
-
- public string Server;
-
- public string Share;
-
- public string Link;
-
- public string Path;
-
- public bool ResolveHashes;
-
- public long Expiration;
-
- internal DfsReferral Next;
-
- internal IDictionary<string, DfsReferral> Map;
-
- internal string Key = null;
-
- public DfsReferral()
- {
- // Server
- // Share
- // Path relative to tree from which this referral was thrown
- Next = this;
- }
-
- internal virtual void Append(DfsReferral dr)
- {
- dr.Next = Next;
- Next = dr;
- }
-
- public override string ToString()
- {
- return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share="
- + Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" +
- Expiration + ",resolveHashes=" + ResolveHashes + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs
deleted file mode 100644
index d89e5bafa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public static class DosError
- {
- public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked(
- (int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)(
- 0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a
- )) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
- new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(
- 0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked(
- (int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)(
- 0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2
- )) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
- new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked(
- 0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked(
- (int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)(
- 0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc
- )) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
- new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked(
- 0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked(
- (int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)(
- 0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035
- )) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
- new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked(
- 0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked(
- (int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)(
- 0xC0000071)) } };
-
- public static string[] DosErrorMessages = { "The operation completed successfully."
- , "Incorrect function.", "Incorrect function.", "The system cannot find the file specified."
- , "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function."
- , "Access is denied.", "The TID specified was invalid.", "The handle is invalid."
- , "The network name cannot be found.", "Not enough storage is available to process this command."
- , "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning."
- , "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process."
- , "The process cannot access the file because it is being used by another process."
- , "The process cannot access the file because another process has locked a portion of the file."
- , "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found."
- , "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session."
- , "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended."
- , "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty."
- , "Cannot create a file when that file already exists.", "All pipe instances are busy."
- , "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available."
- , "This user account has expired.", "The user is not allowed to log on from this workstation."
- , "The user is not allowed to log on at this time.", "The password of this user has expired."
- };
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs
deleted file mode 100644
index bbf7882c8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public class DosFileFilter : ISmbFileFilter
- {
- protected internal string Wildcard;
-
- protected internal int Attributes;
-
- public DosFileFilter(string wildcard, int attributes)
- {
- this.Wildcard = wildcard;
- this.Attributes = attributes;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool Accept(SmbFile file)
- {
- return (file.GetAttributes() & Attributes) != 0;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs
deleted file mode 100644
index bbf3e7cc4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public interface IFileEntry
- {
- string GetName();
-
- int GetType();
-
- int GetAttributes();
-
- long CreateTime();
-
- long LastModified();
-
- long Length();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs
deleted file mode 100644
index b0e40c5cd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal interface IInfo
- {
- int GetAttributes();
-
- long GetCreateTime();
-
- long GetLastWriteTime();
-
- long GetSize();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs
deleted file mode 100644
index b4a02d8c3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class NetServerEnum2 : SmbComTransaction
- {
- internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF));
-
- internal const int SvTypeDomainEnum = unchecked((int)(0x80000000));
-
- internal static readonly string[] Descr = { "WrLehDO\u0000B16BBDz\u0000"
- , "WrLehDz\u0000B16BBDz\u0000" };
-
- internal string Domain;
-
- internal string LastName;
-
- internal int ServerTypes;
-
- internal NetServerEnum2(string domain, int serverTypes)
- {
- this.Domain = domain;
- this.ServerTypes = serverTypes;
- Command = SmbComTransaction;
- SubCommand = NetServerEnum2;
- // not really true be used by upper logic
- Name = "\\PIPE\\LANMAN";
- MaxParameterCount = 8;
- MaxDataCount = 16384;
- MaxSetupCount = unchecked(unchecked(0x00));
- SetupCount = 0;
- Timeout = 5000;
- }
-
- internal override void Reset(int key, string lastName)
- {
- base.Reset();
- this.LastName = lastName;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- byte[] descr;
- int which = SubCommand == NetServerEnum2 ? 0 : 1;
- try
- {
- descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII");
- }
- catch (UnsupportedEncodingException)
- {
- return 0;
- }
- WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex);
- dstIndex += 2;
- Array.Copy(descr, 0, dst, dstIndex, descr.Length);
- dstIndex += descr.Length;
- WriteInt2(unchecked(0x0001), dst, dstIndex);
- dstIndex += 2;
- WriteInt2(MaxDataCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(ServerTypes, dst, dstIndex);
- dstIndex += 4;
- dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false);
- if (which == 1)
- {
- dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false);
- }
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes="
- + (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs
deleted file mode 100644
index 9a0e5e3d5..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class NetServerEnum2Response : SmbComTransactionResponse
- {
- internal class ServerInfo1 : IFileEntry
- {
- internal string Name;
-
- internal int VersionMajor;
-
- internal int VersionMinor;
-
- internal int Type;
-
- internal string CommentOrMasterBrowser;
-
- public virtual string GetName()
- {
- return Name;
- }
-
- public new virtual int GetType()
- {
- return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup :
- SmbFile.TypeServer;
- }
-
- public virtual int GetAttributes()
- {
- return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
- }
-
- public virtual long CreateTime()
- {
- return 0L;
- }
-
- public virtual long LastModified()
- {
- return 0L;
- }
-
- public virtual long Length()
- {
- return 0L;
- }
-
- public override string ToString()
- {
- return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString
- (Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
- }
-
- internal ServerInfo1(NetServerEnum2Response enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly NetServerEnum2Response _enclosing;
- }
-
- private int _converter;
-
- private int _totalAvailableEntries;
-
- internal string LastName;
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- int start = bufferIndex;
- Status = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _converter = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- NumEntries = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _totalAvailableEntries = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- return bufferIndex - start;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- ServerInfo1 e = null;
- Results = new ServerInfo1[NumEntries];
- for (int i = 0; i < NumEntries; i++)
- {
- Results[i] = e = new ServerInfo1(this);
- e.Name = ReadString(buffer, bufferIndex, 16, false);
- bufferIndex += 16;
- e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF);
- e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF);
- e.Type = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- int off = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- off = (off & unchecked(0xFFFF)) - _converter;
- off = start + off;
- e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false);
- if (Log.Level >= 4)
- {
- Log.WriteLine(e);
- }
- }
- LastName = NumEntries == 0 ? null : e.Name;
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status
- + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
- + _totalAvailableEntries + ",lastName=" + LastName + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs
deleted file mode 100644
index 1b0c6f931..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class NetShareEnum : SmbComTransaction
- {
- private static readonly string Descr = "WrLeh\u0000B13BWz\u0000";
-
- public NetShareEnum()
- {
- Command = SmbComTransaction;
- SubCommand = NetShareEnum;
- // not really true be used by upper logic
- Name ="\\PIPE\\LANMAN";
- MaxParameterCount = 8;
- // maxDataCount = 4096; why was this set?
- MaxSetupCount = 0x00;
- SetupCount = 0;
- Timeout = 5000;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- byte[] descr;
- try
- {
- //descr = Runtime.GetBytesForString(Descr, "ASCII");
- descr = Runtime.GetBytesForString(Descr, "UTF-8");
- }
- catch (UnsupportedEncodingException)
- {
- return 0;
- }
- WriteInt2(NetShareEnum, dst, dstIndex);
- dstIndex += 2;
- Array.Copy(descr, 0, dst, dstIndex, descr.Length);
- dstIndex += descr.Length;
- WriteInt2(unchecked(0x0001), dst, dstIndex);
- dstIndex += 2;
- WriteInt2(MaxDataCount, dst, dstIndex);
- dstIndex += 2;
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "NetShareEnum[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs
deleted file mode 100644
index 408f8e4d1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class NetShareEnumResponse : SmbComTransactionResponse
- {
- private int _converter;
-
- private int _totalAvailableEntries;
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- int start = bufferIndex;
- Status = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _converter = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- NumEntries = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _totalAvailableEntries = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- return bufferIndex - start;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- SmbShareInfo e;
- UseUnicode = false;
- Results = new SmbShareInfo[NumEntries];
- for (int i = 0; i < NumEntries; i++)
- {
- Results[i] = e = new SmbShareInfo();
- e.NetName = ReadString(buffer, bufferIndex, 13, false);
- bufferIndex += 14;
- e.Type = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- int off = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- off = (off & unchecked(0xFFFF)) - _converter;
- off = start + off;
- e.Remark = ReadString(buffer, off, 128, false);
- if (Log.Level >= 4)
- {
- Log.WriteLine(e);
- }
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status
- + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
- + _totalAvailableEntries + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs
deleted file mode 100644
index 511e7ae84..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public static class NtStatus
- {
- public const int NtStatusOk = unchecked(0x00000000);
-
- public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001));
-
- public const int NtStatusNotImplemented = unchecked((int)(0xC0000002));
-
- public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003));
-
- public const int NtStatusAccessViolation = unchecked((int)(0xC0000005));
-
- public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008));
-
- public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d));
-
- public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e));
-
- public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
-
- public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)
- );
-
- public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
-
- public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023));
-
- public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033));
-
- public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034));
-
- public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035));
-
- public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037));
-
- public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039));
-
- public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a));
-
- public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b));
-
- public const int NtStatusSharingViolation = unchecked((int)(0xC0000043));
-
- public const int NtStatusDeletePending = unchecked((int)(0xC0000056));
-
- public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e));
-
- public const int NtStatusUserExists = unchecked((int)(0xC0000063));
-
- public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064));
-
- public const int NtStatusWrongPassword = unchecked((int)(0xC000006a));
-
- public const int NtStatusLogonFailure = unchecked((int)(0xC000006d));
-
- public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e));
-
- public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f));
-
- public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070));
-
- public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071));
-
- public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072));
-
- public const int NtStatusNoneMapped = unchecked((int)(0xC0000073));
-
- public const int NtStatusInvalidSid = unchecked((int)(0xC0000078));
-
- public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab));
-
- public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac));
-
- public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad));
-
- public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae));
-
- public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0));
-
- public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1));
-
- public const int NtStatusPipeListening = unchecked((int)(0xC00000b3));
-
- public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba));
-
- public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd));
-
- public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9));
-
- public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca));
-
- public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc));
-
- public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0));
-
- public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da));
-
- public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df));
-
- public const int NtStatusNotADirectory = unchecked((int)(0xC0000103));
-
- public const int NtStatusCannotDelete = unchecked((int)(0xC0000121));
-
- public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122));
-
- public const int NtStatusPipeBroken = unchecked((int)(0xC000014b));
-
- public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151));
-
- public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b));
-
- public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b));
-
- public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
-
- public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199
- ));
-
- public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
-
- public const int NtStatusNotFound = unchecked((int)(0xC0000225));
-
- public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234));
-
- public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
-
- public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
- ));
-
- public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful
- , NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation
- , NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice
- , NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied
- , NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound
- , NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid
- , NtStatusObjectPathNotFound, NtStatusObjectPathSyntaxBad, NtStatusSharingViolation
- , NtStatusDeletePending, NtStatusNoLogonServers, NtStatusUserExists, NtStatusNoSuchUser
- , NtStatusWrongPassword, NtStatusLogonFailure, NtStatusAccountRestriction
- , NtStatusInvalidLogonHours, NtStatusInvalidWorkstation, NtStatusPasswordExpired
- , NtStatusAccountDisabled, NtStatusNoneMapped, NtStatusInvalidSid, NtStatusInstanceNotAvailable
- , NtStatusPipeNotAvailable, NtStatusInvalidPipeState, NtStatusPipeBusy
- , NtStatusPipeDisconnected, NtStatusPipeClosing, NtStatusPipeListening,
- NtStatusFileIsADirectory, NtStatusDuplicateName, NtStatusNetworkNameDeleted
- , NtStatusNetworkAccessDenied, NtStatusBadNetworkName, NtStatusRequestNotAccepted
- , NtStatusCantAccessDomainInfo, NtStatusNoSuchDomain, NtStatusNotADirectory
- , NtStatusCannotDelete, NtStatusInvalidComputerName, NtStatusPipeBroken
- , NtStatusNoSuchAlias, NtStatusLogonTypeNotGranted, NtStatusNoTrustSamAccount
- , NtStatusTrustedDomainFailure, NtStatusNologonWorkstationTrustAccount,
- NtStatusPasswordMustChange, NtStatusNotFound, NtStatusAccountLockedOut
- , NtStatusPathNotCovered, NtStatusIoReparseTagNotHandled };
-
- public static string[] NtStatusMessages = { "The operation completed successfully."
- , "A device attached to the system is not functioning.", "Incorrect function.",
- "The parameter is incorrect.", "Invalid access to memory location.", "The handle is invalid."
- , "The parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified."
- , "More data is available.", "Access is denied.", "The data area passed to a system call is too small."
- , "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified."
- , "Cannot create a file when that file already exists.", "The handle is invalid."
- , "The specified path is invalid.", "The system cannot find the path specified."
- , "The specified path is invalid.", "The process cannot access the file because it is being used by another process."
- , "Access is denied.", "There are currently no logon servers available to service the logon request."
- , "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct."
- , "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction."
- , "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer."
- , "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled."
- , "No mapping between account names and security IDs was done.", "The security ID structure is invalid."
- , "All pipe instances are busy.", "All pipe instances are busy.", "The pipe state is invalid."
- , "All pipe instances are busy.", "No process is on the other end of the pipe.",
- "The pipe is being closed.", "Waiting for a process to open the other end of the pipe."
- , "Access is denied.", "A duplicate name exists on the network.", "The specified network name is no longer available."
- , "Network access is denied.", "The network name cannot be found.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."
- , "Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved."
- , "The specified domain did not exist.", "The directory name is invalid.", "Access is denied."
- , "The format of the specified computer name is invalid.", "The pipe has been ended."
- , "The specified local group does not exist.", "Logon failure: the user has not been granted the requested logon type at this computer."
- , "The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship."
- , "The trust relationship between the primary domain and the trusted domain failed."
- , "The account used is a Computer Account. Use your global user account or local user account to access this server."
- , "The user must change his password before he logs on the first time.", "NT_STATUS_NOT_FOUND"
- , "The referenced account is currently locked out and may not be logged on to.",
- "The remote system is not reachable by the transport.", "NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED"
- };
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs
deleted file mode 100644
index 6a83543b1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class NtTransQuerySecurityDesc : SmbComNtTransaction
- {
- internal int Fid;
-
- internal int SecurityInformation;
-
- internal NtTransQuerySecurityDesc(int fid, int securityInformation)
- {
- this.Fid = fid;
- this.SecurityInformation = securityInformation;
- Command = SmbComNtTransact;
- Function = NtTransactQuerySecurityDesc;
- SetupCount = 0;
- TotalDataCount = 0;
- MaxParameterCount = 4;
- MaxDataCount = 32768;
- MaxSetupCount = unchecked(unchecked(0x00));
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(Fid, dst, dstIndex);
- dstIndex += 2;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved
- WriteInt4(SecurityInformation, dst, dstIndex);
- dstIndex += 4;
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump
- .ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation
- , 8) + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs
deleted file mode 100644
index 9365d5154..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse
- {
- internal SecurityDescriptor SecurityDescriptor;
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- Length = ReadInt4(buffer, bufferIndex);
- return 4;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- if (ErrorCode != 0)
- {
- return 4;
- }
- try
- {
- SecurityDescriptor = new SecurityDescriptor();
- bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len);
- }
- catch (IOException ioe)
- {
- throw new RuntimeException(ioe.Message);
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "NtTransQuerySecurityResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs
deleted file mode 100644
index 853364f8e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- /// <summary>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
- /// </summary>
- /// <remarks>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for complete details.
- /// </remarks>
- public abstract class NtlmAuthenticator
- {
- private static NtlmAuthenticator _auth;
-
- private string _url;
-
- private SmbAuthException _sae;
-
- private void Reset()
- {
- _url = null;
- _sae = null;
- }
-
- /// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
- /// <remarks>Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
- /// </remarks>
- public static void SetDefault(NtlmAuthenticator a)
- {
- lock (typeof(NtlmAuthenticator))
- {
- if (_auth != null)
- {
- return;
- }
- _auth = a;
- }
- }
-
- protected internal string GetRequestingUrl()
- {
- return _url;
- }
-
- protected internal SmbAuthException GetRequestingException()
- {
- return _sae;
- }
-
- /// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
- /// </summary>
- /// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
- /// </remarks>
- public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
- url, SmbAuthException sae)
- {
- if (_auth == null)
- {
- return null;
- }
- lock (_auth)
- {
- _auth._url = url;
- _auth._sae = sae;
- return _auth.GetNtlmPasswordAuthentication();
- }
- }
-
- /// <summary>An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
- /// </summary>
- /// <remarks>
- /// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
- /// If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>.
- /// </remarks>
- protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication
- ()
- {
- return null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs
deleted file mode 100644
index 745b1f663..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
-
- public sealed class NtlmChallenge
- {
- public byte[] Challenge;
-
- public UniAddress Dc;
-
- internal NtlmChallenge(byte[] challenge, UniAddress dc)
- {
- this.Challenge = challenge;
- this.Dc = dc;
- }
-
- public override string ToString()
- {
- return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge
- .Length * 2) + ",dc=" + Dc + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs
deleted file mode 100644
index 44266f974..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs
+++ /dev/null
@@ -1,206 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Ntlmssp;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>For initiating NTLM authentication (including NTLMv2).</summary>
- /// <remarks>For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication.
- /// </remarks>
- public class NtlmContext
- {
- internal NtlmPasswordAuthentication Auth;
-
- internal int NtlmsspFlags;
-
- internal string Workstation;
-
- internal bool isEstablished;
-
- internal byte[] ServerChallenge;
-
- internal byte[] SigningKey;
-
- internal string NetbiosName = null;
-
- internal int State = 1;
-
- internal LogStream Log;
-
- public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
- {
- this.Auth = auth;
- NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2
- | NtlmFlags.NtlmsspNegotiate128;
- if (doSigning)
- {
- NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign
- | NtlmFlags.NtlmsspNegotiateKeyExch;
- }
- Workstation = Type1Message.GetDefaultWorkstation();
- Log = LogStream.GetInstance();
- }
-
- public override string ToString()
- {
- string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString
- (NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished
- + ",state=" + State + ",serverChallenge=";
- if (ServerChallenge == null)
- {
- ret += "null";
- }
- else
- {
- ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2);
- }
- ret += ",signingKey=";
- if (SigningKey == null)
- {
- ret += "null";
- }
- else
- {
- ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2);
- }
- ret += "]";
- return ret;
- }
-
- public virtual bool IsEstablished()
- {
- return isEstablished;
- }
-
- public virtual byte[] GetServerChallenge()
- {
- return ServerChallenge;
- }
-
- public virtual byte[] GetSigningKey()
- {
- return SigningKey;
- }
-
- public virtual string GetNetbiosName()
- {
- return NetbiosName;
- }
-
- private string GetNtlmsspListItem(byte[] type2Token, int id0)
- {
- int ri = 58;
- for (; ; )
- {
- int id = Encdec.Dec_uint16le(type2Token, ri);
- int len = Encdec.Dec_uint16le(type2Token, ri + 2);
- ri += 4;
- if (id == 0 || (ri + len) > type2Token.Length)
- {
- break;
- }
- if (id == id0)
- {
- try
- {
- return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding
- );
- }
- catch (UnsupportedEncodingException)
- {
- break;
- }
- }
- ri += len;
- }
- return null;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual byte[] InitSecContext(byte[] token, int offset, int len)
- {
- switch (State)
- {
- case 1:
- {
- Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation);
- token = msg1.ToByteArray();
- if (Log.Level >= 4)
- {
- Log.WriteLine(msg1);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, token, 0, token.Length);
- }
- }
- State++;
- break;
- }
-
- case 2:
- {
- try
- {
- Type2Message msg2 = new Type2Message(token);
- if (Log.Level >= 4)
- {
- Log.WriteLine(msg2);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, token, 0, token.Length);
- }
- }
- ServerChallenge = msg2.GetChallenge();
- NtlmsspFlags &= msg2.GetFlags();
- // netbiosName = getNtlmsspListItem(token, 0x0001);
- Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(),
- Auth.GetUsername(), Workstation, NtlmsspFlags);
- token = msg3.ToByteArray();
- if (Log.Level >= 4)
- {
- Log.WriteLine(msg3);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, token, 0, token.Length);
- }
- }
- if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0)
- {
- SigningKey = msg3.GetMasterKey();
- }
- isEstablished = true;
- State++;
- break;
- }
- catch (Exception e)
- {
- throw new SmbException(e.Message, e);
- }
- }
-
- default:
- {
- throw new SmbException("Invalid state");
- }
- }
- return token;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs
deleted file mode 100644
index ec3899fe9..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs
+++ /dev/null
@@ -1,807 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>This class stores and encrypts NTLM user credentials.</summary>
- /// <remarks>
- /// This class stores and encrypts NTLM user credentials. The default
- /// credentials are retrieved from the <tt>jcifs.smb.client.domain</tt>,
- /// <tt>jcifs.smb.client.username</tt>, and <tt>jcifs.smb.client.password</tt>
- /// properties.
- /// <p>
- /// Read <a href="../../../authhandler.html">jCIFS Exceptions and
- /// NtlmAuthenticator</a> for related information.
- /// </remarks>
-
- public sealed class NtlmPasswordAuthentication : Principal
- {
- private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility"
- , 3);
-
- private static readonly Random Random = new Random();
-
- private static LogStream _log = LogStream.GetInstance();
-
- private static readonly byte[] S8 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) };
-
- // KGS!@#$%
- private static void E(byte[] key, byte[] data, byte[] e)
- {
- byte[] key7 = new byte[7];
- byte[] e8 = new byte[8];
- for (int i = 0; i < key.Length / 7; i++)
- {
- Array.Copy(key, i * 7, key7, 0, 7);
- DES des = new DES(key7);
- des.Encrypt(data, e8);
- Array.Copy(e8, 0, e, i * 8, 8);
- }
- }
-
- internal static string DefaultDomain;
-
- internal static string DefaultUsername;
-
- internal static string DefaultPassword;
-
- internal static readonly string Blank = string.Empty;
-
- public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication
- (string.Empty, string.Empty, string.Empty);
-
- internal static void InitDefaults()
- {
- if (DefaultDomain != null)
- {
- return;
- }
- DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", "?");
- DefaultUsername = Config.GetProperty("jcifs.smb.client.username", "GUEST");
- DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
- }
-
- /// <summary>Generate the ANSI DES hash for the password associated with these credentials.
- /// </summary>
- /// <remarks>Generate the ANSI DES hash for the password associated with these credentials.
- /// </remarks>
- public static byte[] GetPreNtlmResponse(string password, byte[] challenge)
- {
- byte[] p14 = new byte[14];
- byte[] p21 = new byte[21];
- byte[] p24 = new byte[24];
- byte[] passwordBytes;
- try
- {
- passwordBytes = Runtime.GetBytesForString(password.ToUpper(), SmbConstants.OemEncoding);
- }
- catch (UnsupportedEncodingException uee)
- {
- throw new RuntimeException("Try setting jcifs.encoding=US-ASCII", uee);
- }
- int passwordLength = passwordBytes.Length;
- // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
- if (passwordLength > 14)
- {
- passwordLength = 14;
- }
- Array.Copy(passwordBytes, 0, p14, 0, passwordLength);
- E(p14, S8, p21);
- E(p21, challenge, p24);
- return p24;
- }
-
- /// <summary>Generate the Unicode MD4 hash for the password associated with these credentials.
- /// </summary>
- /// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials.
- /// </remarks>
- public static byte[] GetNtlmResponse(string password, byte[] challenge)
- {
- byte[] uni = null;
- byte[] p21 = new byte[21];
- byte[] p24 = new byte[24];
- try
- {
- uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding);
- }
- catch (UnsupportedEncodingException uee)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(uee, _log);
- }
- }
- Md4 md4 = new Md4();
- md4.Update(uni);
- try
- {
- md4.Digest(p21, 0, 16);
- }
- catch (Exception ex)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, _log);
- }
- }
- E(p21, challenge, p24);
- return p24;
- }
-
- /// <summary>Creates the LMv2 response for the supplied information.</summary>
- /// <remarks>Creates the LMv2 response for the supplied information.</remarks>
- /// <param name="domain">The domain in which the username exists.</param>
- /// <param name="user">The username.</param>
- /// <param name="password">The user's password.</param>
- /// <param name="challenge">The server challenge.</param>
- /// <param name="clientChallenge">The client challenge (nonce).</param>
- public static byte[] GetLMv2Response(string domain, string user, string password,
- byte[] challenge, byte[] clientChallenge)
- {
- try
- {
- byte[] hash = new byte[16];
- byte[] response = new byte[24];
- // The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
- Md4 md4 = new Md4();
- md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
- );
- Hmact64 hmac = new Hmact64(md4.Digest());
- hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding
- ));
- hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding
- ));
- hmac = new Hmact64(hmac.Digest());
- hmac.Update(challenge);
- hmac.Update(clientChallenge);
- hmac.Digest(response, 0, 16);
- Array.Copy(clientChallenge, 0, response, 16, 8);
- return response;
- }
- catch (Exception ex)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, _log);
- }
- return null;
- }
- }
-
- public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte
- [] clientChallenge)
- {
- byte[] sessionHash = new byte[8];
- try
- {
- MessageDigest md5;
- md5 = MessageDigest.GetInstance("MD5");
- md5.Update(serverChallenge);
- md5.Update(clientChallenge, 0, 8);
- Array.Copy(md5.Digest(), 0, sessionHash, 0, 8);
- }
- catch (Exception gse)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(gse, _log);
- }
- throw new RuntimeException("MD5", gse);
- }
- byte[] key = new byte[21];
- Array.Copy(nTowFv1, 0, key, 0, 16);
- byte[] ntResponse = new byte[24];
- E(key, sessionHash, ntResponse);
- return ntResponse;
- }
-
- public static byte[] NtowFv1(string password)
- {
- if (password == null)
- {
- throw new RuntimeException("Password parameter is required");
- }
- try
- {
- Md4 md4 = new Md4();
- md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
- );
- return md4.Digest();
- }
- catch (UnsupportedEncodingException uee)
- {
- throw new RuntimeException(uee.Message);
- }
- }
-
- public static byte[] NtowFv2(string domain, string username, string password)
- {
- try
- {
- Md4 md4 = new Md4();
- md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
- );
- Hmact64 hmac = new Hmact64(md4.Digest());
- hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding
- ));
- hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
- return hmac.Digest();
- }
- catch (UnsupportedEncodingException uee)
- {
- throw new RuntimeException(uee.Message);
- }
- }
-
- internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge
- , byte[] clientData, int offset, int length)
- {
- Hmact64 hmac = new Hmact64(responseKey);
- hmac.Update(serverChallenge);
- hmac.Update(clientData, offset, length);
- byte[] mac = hmac.Digest();
- byte[] ret = new byte[mac.Length + clientData.Length];
- Array.Copy(mac, 0, ret, 0, mac.Length);
- Array.Copy(clientData, 0, ret, mac.Length, clientData.Length);
- return ret;
- }
-
- public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge
- , byte[] clientChallenge)
- {
- return ComputeResponse(responseKeyLm, serverChallenge
- , clientChallenge, 0, clientChallenge.Length);
- }
-
- public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge
- , byte[] clientChallenge, long nanos1601, byte[] targetInfo)
- {
- int targetInfoLength = targetInfo != null ? targetInfo.Length : 0;
- byte[] temp = new byte[28 + targetInfoLength + 4];
- Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0);
- // Header
- Encdec.Enc_uint32le(unchecked(0x00000000), temp, 4);
- // Reserved
- Encdec.Enc_uint64le(nanos1601, temp, 8);
- Array.Copy(clientChallenge, 0, temp, 16, 8);
- Encdec.Enc_uint32le(unchecked(0x00000000), temp, 24);
- // Unknown
- if (targetInfo != null)
- {
- Array.Copy(targetInfo, 0, temp, 28, targetInfoLength);
- }
- Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength);
- // mystery bytes!
- return ComputeResponse(responseKeyNt, serverChallenge
- , temp, 0, temp.Length);
- }
-
- internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication
- (string.Empty, string.Empty, string.Empty);
-
- internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication
- ("?", "GUEST", string.Empty);
-
- internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication
- (null);
-
- internal string Domain;
-
- internal string Username;
-
- internal string Password;
-
- internal byte[] AnsiHash;
-
- internal byte[] UnicodeHash;
-
- internal bool HashesExternal;
-
- internal byte[] ClientChallenge;
-
- internal byte[] Challenge;
-
- /// <summary>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
- /// component of an SMB URL like "<tt>domain;user:pass</tt>".
- /// </summary>
- /// <remarks>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
- /// component of an SMB URL like "<tt>domain;user:pass</tt>". This constructor
- /// is used internally be jCIFS when parsing SMB URLs.
- /// </remarks>
- public NtlmPasswordAuthentication(string userInfo)
- {
- Domain = Username = Password = null;
- if (userInfo != null)
- {
- try
- {
- userInfo = Unescape(userInfo);
- }
- catch (UnsupportedEncodingException)
- {
- }
- int i;
- int u;
- int end;
- char c;
- end = userInfo.Length;
- for (i = 0, u = 0; i < end; i++)
- {
- c = userInfo[i];
- if (c == ';')
- {
- Domain = Runtime.Substring(userInfo, 0, i);
- u = i + 1;
- }
- else
- {
- if (c == ':')
- {
- Password = Runtime.Substring(userInfo, i + 1);
- break;
- }
- }
- }
- Username = Runtime.Substring(userInfo, u, i);
- }
- InitDefaults();
- if (Domain == null)
- {
- Domain = DefaultDomain;
- }
- if (Username == null)
- {
- Username = DefaultUsername;
- }
- if (Password == null)
- {
- Password = DefaultPassword;
- }
- }
-
- /// <summary>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object from a
- /// domain, username, and password.
- /// </summary>
- /// <remarks>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object from a
- /// domain, username, and password. Parameters that are <tt>null</tt>
- /// will be substituted with <tt>jcifs.smb.client.domain</tt>,
- /// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
- /// property values.
- /// </remarks>
- public NtlmPasswordAuthentication(string domain, string username, string password
- )
- {
- int ci;
- if (username != null)
- {
- ci = username.IndexOf('@');
- if (ci > 0)
- {
- domain = Runtime.Substring(username, ci + 1);
- username = Runtime.Substring(username, 0, ci);
- }
- else
- {
- ci = username.IndexOf('\\');
- if (ci > 0)
- {
- domain = Runtime.Substring(username, 0, ci);
- username = Runtime.Substring(username, ci + 1);
- }
- }
- }
- this.Domain = domain;
- this.Username = username;
- this.Password = password;
- InitDefaults();
- if (domain == null)
- {
- this.Domain = DefaultDomain;
- }
- if (username == null)
- {
- this.Username = DefaultUsername;
- }
- if (password == null)
- {
- this.Password = DefaultPassword;
- }
- }
-
- /// <summary>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
- /// hashes.
- /// </summary>
- /// <remarks>
- /// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
- /// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
- /// class which is in turn used by NTLM HTTP authentication functionality.
- /// </remarks>
- public NtlmPasswordAuthentication(string domain, string username, byte[] challenge
- , byte[] ansiHash, byte[] unicodeHash)
- {
- if (domain == null || username == null || ansiHash == null || unicodeHash == null)
- {
- throw new ArgumentException("External credentials cannot be null");
- }
- this.Domain = domain;
- this.Username = username;
- Password = null;
- this.Challenge = challenge;
- this.AnsiHash = ansiHash;
- this.UnicodeHash = unicodeHash;
- HashesExternal = true;
- }
-
- /// <summary>Returns the domain.</summary>
- /// <remarks>Returns the domain.</remarks>
- public string GetDomain()
- {
- return Domain;
- }
-
- /// <summary>Returns the username.</summary>
- /// <remarks>Returns the username.</remarks>
- public string GetUsername()
- {
- return Username;
- }
-
- /// <summary>
- /// Returns the password in plain text or <tt>null</tt> if the raw password
- /// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
- /// object which will be the case when NTLM HTTP Authentication is
- /// used.
- /// </summary>
- /// <remarks>
- /// Returns the password in plain text or <tt>null</tt> if the raw password
- /// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
- /// object which will be the case when NTLM HTTP Authentication is
- /// used. There is no way to retrieve a users password in plain text unless
- /// it is supplied by the user at runtime.
- /// </remarks>
- public string GetPassword()
- {
- return Password;
- }
-
- /// <summary>
- /// Return the domain and username in the format:
- /// <tt>domain\\username</tt>.
- /// </summary>
- /// <remarks>
- /// Return the domain and username in the format:
- /// <tt>domain\\username</tt>. This is equivalent to <tt>toString()</tt>.
- /// </remarks>
- public new string GetName()
- {
- bool d = Domain.Length > 0 && Domain.Equals("?") == false;
- return d ? Domain + "\\" + Username : Username;
- }
-
- /// <summary>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
- /// </summary>
- /// <remarks>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
- /// </remarks>
- public byte[] GetAnsiHash(byte[] challenge)
- {
- if (HashesExternal)
- {
- return AnsiHash;
- }
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- {
- return GetPreNtlmResponse(Password, challenge);
- }
-
- case 2:
- {
- return GetNtlmResponse(Password, challenge);
- }
-
- case 3:
- case 4:
- case 5:
- {
- if (ClientChallenge == null)
- {
- ClientChallenge = new byte[8];
- Random.NextBytes(ClientChallenge);
- }
- return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge);
- }
-
- default:
- {
- return GetPreNtlmResponse(Password, challenge);
- }
- }
- }
-
- /// <summary>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
- /// </summary>
- /// <remarks>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
- /// </remarks>
- public byte[] GetUnicodeHash(byte[] challenge)
- {
- if (HashesExternal)
- {
- return UnicodeHash;
- }
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- case 2:
- {
- return GetNtlmResponse(Password, challenge);
- }
-
- case 3:
- case 4:
- case 5:
- {
- return new byte[0];
- }
-
- default:
- {
- return GetNtlmResponse(Password, challenge);
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public byte[] GetSigningKey(byte[] challenge)
- {
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- case 2:
- {
- byte[] signingKey = new byte[40];
- GetUserSessionKey(challenge, signingKey, 0);
- Array.Copy(GetUnicodeHash(challenge), 0, signingKey, 16, 24);
- return signingKey;
- }
-
- case 3:
- case 4:
- case 5:
- {
- throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)"
- );
- }
- }
- return null;
- }
-
- /// <summary>Returns the effective user session key.</summary>
- /// <remarks>Returns the effective user session key.</remarks>
- /// <param name="challenge">The server challenge.</param>
- /// <returns>
- /// A <code>byte[]</code> containing the effective user session key,
- /// used in SMB MAC signing and NTLMSSP signing and sealing.
- /// </returns>
- public byte[] GetUserSessionKey(byte[] challenge)
- {
- if (HashesExternal)
- {
- return null;
- }
- byte[] key = new byte[16];
- try
- {
- GetUserSessionKey(challenge, key, 0);
- }
- catch (Exception ex)
- {
- if (_log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, _log);
- }
- }
- return key;
- }
-
- /// <summary>Calculates the effective user session key.</summary>
- /// <remarks>Calculates the effective user session key.</remarks>
- /// <param name="challenge">The server challenge.</param>
- /// <param name="dest">
- /// The destination array in which the user session key will be
- /// placed.
- /// </param>
- /// <param name="offset">
- /// The offset in the destination array at which the
- /// session key will start.
- /// </param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset)
- {
- if (HashesExternal)
- {
- return;
- }
- try
- {
- Md4 md4 = new Md4();
- md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)
- );
- switch (LmCompatibility)
- {
- case 0:
- case 1:
- case 2:
- {
- md4.Update(md4.Digest());
- md4.Digest(dest, offset, 16);
- break;
- }
-
- case 3:
- case 4:
- case 5:
- {
- if (ClientChallenge == null)
- {
- ClientChallenge = new byte[8];
- Random.NextBytes(ClientChallenge);
- }
- Hmact64 hmac = new Hmact64(md4.Digest());
- hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding
- ));
- hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding
- ));
- byte[] ntlmv2Hash = hmac.Digest();
- hmac = new Hmact64(ntlmv2Hash);
- hmac.Update(challenge);
- hmac.Update(ClientChallenge);
- Hmact64 userKey = new Hmact64(ntlmv2Hash);
- userKey.Update(hmac.Digest());
- userKey.Digest(dest, offset, 16);
- break;
- }
-
- default:
- {
- md4.Update(md4.Digest());
- md4.Digest(dest, offset, 16);
- break;
- }
- }
- }
- catch (Exception e)
- {
- throw new SmbException(string.Empty, e);
- }
- }
-
- /// <summary>
- /// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
- /// equality.
- /// </summary>
- /// <remarks>
- /// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
- /// equality. Two <tt>NtlmPasswordAuthentication</tt> objects are equal if
- /// their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one <tt>NtlmPasswordAuthentication</tt> object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method.
- /// </remarks>
- public override bool Equals(object obj)
- {
- if (obj is NtlmPasswordAuthentication)
- {
- NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication
- )obj;
- if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals
- (Username.ToUpper()))
- {
- if (HashesExternal && ntlm.HashesExternal)
- {
-
- return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm.
- UnicodeHash);
- }
- if (!HashesExternal && Password.Equals(ntlm.Password))
- {
- return true;
- }
- }
- }
- return false;
- }
-
- /// <summary>Return the upcased username hash code.</summary>
- /// <remarks>Return the upcased username hash code.</remarks>
- public override int GetHashCode()
- {
- return GetName().ToUpper().GetHashCode();
- }
-
- /// <summary>
- /// Return the domain and username in the format:
- /// <tt>domain\\username</tt>.
- /// </summary>
- /// <remarks>
- /// Return the domain and username in the format:
- /// <tt>domain\\username</tt>. This is equivalent to <tt>getName()</tt>.
- /// </remarks>
- public override string ToString()
- {
- return GetName();
- }
-
- /// <exception cref="System.FormatException"></exception>
- /// <exception cref="UnsupportedEncodingException"></exception>
- internal static string Unescape(string str)
- {
- char ch;
- int i;
- int j;
- int state;
- int len;
- char[] @out;
- byte[] b = new byte[1];
- if (str == null)
- {
- return null;
- }
- len = str.Length;
- @out = new char[len];
- state = 0;
- for (i = j = 0; i < len; i++)
- {
- switch (state)
- {
- case 0:
- {
- ch = str[i];
- if (ch == '%')
- {
- state = 1;
- }
- else
- {
- @out[j++] = ch;
- }
- break;
- }
-
- case 1:
- {
- b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i,
- i + 2), 16) & unchecked(0xFF)));
- @out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0];
- i++;
- state = 0;
- break;
- }
- }
- }
- return new string(@out, 0, j);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs
deleted file mode 100644
index 14a5479e3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public class Principal
- {
- private string _name = "";
-
- public string GetName()
- {
- return _name;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs
deleted file mode 100644
index a6ad59fb1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs
+++ /dev/null
@@ -1,900 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using SharpCifs.Dcerpc;
-using SharpCifs.Dcerpc.Msrpc;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-using Hashtable = SharpCifs.Util.Sharpen.Hashtable; //not System.Collections.Hashtable
-
-namespace SharpCifs.Smb
-{
- /// <summary>
- /// A Windows SID is a numeric identifier used to represent Windows
- /// accounts.
- /// </summary>
- /// <remarks>
- /// A Windows SID is a numeric identifier used to represent Windows
- /// accounts. SIDs are commonly represented using a textual format such as
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt> but they may
- /// also be resolved to yield the name of the associated Windows account
- /// such as <tt>Administrators</tt> or <tt>MYDOM\alice</tt>.
- /// <p>
- /// Consider the following output of <tt>examples/SidLookup.java</tt>:
- /// <pre>
- /// toString: S-1-5-21-4133388617-793952518-2001621813-512
- /// toDisplayString: WNET\Domain Admins
- /// getType: 2
- /// getTypeText: Domain group
- /// getDomainName: WNET
- /// getAccountName: Domain Admins
- /// </pre>
- /// </remarks>
- public class Sid : Rpc.SidT
- {
- public const int SidTypeUseNone = Lsarpc.SidNameUseNone;
-
- public const int SidTypeUser = Lsarpc.SidNameUser;
-
- public const int SidTypeDomGrp = Lsarpc.SidNameDomGrp;
-
- public const int SidTypeDomain = Lsarpc.SidNameDomain;
-
- public const int SidTypeAlias = Lsarpc.SidNameAlias;
-
- public const int SidTypeWknGrp = Lsarpc.SidNameWknGrp;
-
- public const int SidTypeDeleted = Lsarpc.SidNameDeleted;
-
- public const int SidTypeInvalid = Lsarpc.SidNameInvalid;
-
- public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
-
- internal static readonly string[] SidTypeNames = { "0", "User", "Domain group"
- , "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" };
-
- public const int SidFlagResolveSids = unchecked(0x0001);
-
- public static Sid Everyone;
-
- public static Sid CreatorOwner;
-
- public static Sid SYSTEM;
-
- static Sid()
- {
- try
- {
- Everyone = new Sid("S-1-1-0");
- CreatorOwner = new Sid("S-1-3-0");
- SYSTEM = new Sid("S-1-5-18");
- }
- catch (SmbException)
- {
- }
- }
-
- internal static Hashtable SidCache = new Hashtable();
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle
- , Sid[] sids)
- {
- MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
- handle.Sendrecv(rpc);
- switch (rpc.Retval)
- {
- case 0:
- case NtStatus.NtStatusNoneMapped:
- case unchecked(0x00000107):
- {
- // NT_STATUS_SOME_NOT_MAPPED
- break;
- }
-
- default:
- {
- throw new SmbException(rpc.Retval, false);
- }
- }
- for (int si = 0; si < sids.Length; si++)
- {
- sids[si].Type = rpc.Names.Names[si].SidType;
- sids[si].DomainName = null;
- switch (sids[si].Type)
- {
- case SidTypeUser:
- case SidTypeDomGrp:
- case SidTypeDomain:
- case SidTypeAlias:
- case SidTypeWknGrp:
- {
- int sidIndex = rpc.Names.Names[si].SidIndex;
- Rpc.Unicode_string ustr = rpc.Domains.Domains[sidIndex].Name;
- sids[si].DomainName = (new UnicodeString(ustr, false)).ToString();
- break;
- }
- }
- sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString
- ();
- sids[si].OriginServer = null;
- sids[si].OriginAuth = null;
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication
- auth, Sid[] sids)
- {
- DcerpcHandle handle = null;
- LsaPolicyHandle policyHandle = null;
- lock (SidCache)
- {
- try
- {
- handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]"
- , auth);
- string server = authorityServerName;
- int dot = server.IndexOf('.');
- if (dot > 0 && char.IsDigit(server[0]) == false)
- {
- server = Runtime.Substring(server, 0, dot);
- }
- policyHandle = new LsaPolicyHandle(handle, "\\\\" + server, unchecked(0x00000800));
- ResolveSids(handle, policyHandle, sids);
- }
- finally
- {
- if (handle != null)
- {
- if (policyHandle != null)
- {
- policyHandle.Close();
- }
- handle.Close();
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
- auth, Sid[] sids, int offset, int length)
- {
- List<object> list = new List<object>();//new List<object>(sids.Length);
- int si;
- lock (SidCache)
- {
- for (si = 0; si < length; si++)
- {
- Sid sid = (Sid)SidCache.Get(sids[offset + si]);
- if (sid != null)
- {
- sids[offset + si].Type = sid.Type;
- sids[offset + si].DomainName = sid.DomainName;
- sids[offset + si].AcctName = sid.AcctName;
- }
- else
- {
- list.Add(sids[offset + si]);
- }
- }
- if (list.Count > 0)
- {
- //sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
- sids = (Sid[])list.ToArray();
- ResolveSids0(authorityServerName, auth, sids);
- for (si = 0; si < sids.Length; si++)
- {
- SidCache.Put(sids[si], sids[si]);
- }
- }
- }
- }
-
- /// <summary>Resolve an array of SIDs using a cache and at most one MSRPC request.</summary>
- /// <remarks>
- /// Resolve an array of SIDs using a cache and at most one MSRPC request.
- /// <p>
- /// This method will attempt
- /// to resolve SIDs using a cache and cache the results of any SIDs that
- /// required resolving with the authority. SID cache entries are currently not
- /// expired because under normal circumstances SID information never changes.
- /// </remarks>
- /// <param name="authorityServerName">The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority.
- /// </param>
- /// <param name="auth">The credentials that should be used to communicate with the named server. As usual, <tt>null</tt> indicates that default credentials should be used.
- /// </param>
- /// <param name="sids">The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the <tt>toDisplayString</tt>, <tt>getDomainName</tt>, and <tt>getAccountName</tt> methods.
- /// </param>
- /// <exception cref="System.IO.IOException"></exception>
- public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
- auth, Sid[] sids)
- {
- List<object> list = new List<object>();//new List<object>(sids.Length);
- int si;
- lock (SidCache)
- {
- for (si = 0; si < sids.Length; si++)
- {
- Sid sid = (Sid)SidCache.Get(sids[si]);
- if (sid != null)
- {
- sids[si].Type = sid.Type;
- sids[si].DomainName = sid.DomainName;
- sids[si].AcctName = sid.AcctName;
- }
- else
- {
- list.Add(sids[si]);
- }
- }
- if (list.Count > 0)
- {
- //sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
- sids = (Sid[]) list.ToArray();
- ResolveSids0(authorityServerName, auth, sids);
- for (si = 0; si < sids.Length; si++)
- {
- SidCache.Put(sids[si], sids[si]);
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static Sid GetServerSid(string server, NtlmPasswordAuthentication
- auth)
- {
- DcerpcHandle handle = null;
- LsaPolicyHandle policyHandle = null;
- Lsarpc.LsarDomainInfo info = new Lsarpc.LsarDomainInfo();
- MsrpcQueryInformationPolicy rpc;
- lock (SidCache)
- {
- try
- {
- handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth);
- // NetApp doesn't like the 'generic' access mask values
- policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001));
- rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain
- , info);
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- return new Sid(info.Sid, SidTypeDomain, (new UnicodeString
- (info.Name, false)).ToString(), null, false);
- }
- finally
- {
- if (handle != null)
- {
- if (policyHandle != null)
- {
- policyHandle.Close();
- }
- handle.Close();
- }
- }
- }
- }
-
- public static byte[] ToByteArray(Rpc.SidT sid)
- {
- byte[] dst = new byte[1 + 1 + 6 + sid.SubAuthorityCount * 4];
- int di = 0;
- dst[di++] = sid.Revision;
- dst[di++] = sid.SubAuthorityCount;
- Array.Copy(sid.IdentifierAuthority, 0, dst, di, 6);
- di += 6;
- for (int ii = 0; ii < sid.SubAuthorityCount; ii++)
- {
- Encdec.Enc_uint32le(sid.SubAuthority[ii], dst, di);
- di += 4;
- }
- return dst;
- }
-
- internal int Type;
-
- internal string DomainName;
-
- internal string AcctName;
-
- internal string OriginServer;
-
- internal NtlmPasswordAuthentication OriginAuth;
-
- public Sid(byte[] src, int si)
- {
- Revision = src[si++];
- SubAuthorityCount = src[si++];
- IdentifierAuthority = new byte[6];
- Array.Copy(src, si, IdentifierAuthority, 0, 6);
- si += 6;
- if (SubAuthorityCount > 100)
- {
- throw new RuntimeException("Invalid SID sub_authority_count");
- }
- SubAuthority = new int[SubAuthorityCount];
- for (int i = 0; i < SubAuthorityCount; i++)
- {
- SubAuthority[i] = ServerMessageBlock.ReadInt4(src, si);
- si += 4;
- }
- }
-
- /// <summary>
- /// Construct a SID from it's textual representation such as
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
- /// </summary>
- /// <remarks>
- /// Construct a SID from it's textual representation such as
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
- /// </remarks>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public Sid(string textual)
- {
- StringTokenizer st = new StringTokenizer(textual, "-");
- if (st.CountTokens() < 3 || !st.NextToken().Equals("S"))
- {
- // need S-N-M
- throw new SmbException("Bad textual SID format: " + textual);
- }
- Revision = byte.Parse(st.NextToken());
- string tmp = st.NextToken();
- long id = 0;
- if (tmp.StartsWith("0x"))
- {
- //id = long.Parse(Sharpen.Runtime.Substring(tmp, 2), 16);
- id = long.Parse(Runtime.Substring(tmp, 2));
- }
- else
- {
- id = long.Parse(tmp);
- }
- IdentifierAuthority = new byte[6];
- for (int i = 5; id > 0; i--)
- {
- IdentifierAuthority[i] = unchecked((byte)(id % 256));
- id >>= 8;
- }
- SubAuthorityCount = unchecked((byte)st.CountTokens());
- if (SubAuthorityCount > 0)
- {
- SubAuthority = new int[SubAuthorityCount];
- for (int i1 = 0; i1 < SubAuthorityCount; i1++)
- {
- SubAuthority[i1] = (int)(long.Parse(st.NextToken()) & unchecked(0xFFFFFFFFL));
- }
- }
- }
-
- /// <summary>
- /// Construct a SID from a domain SID and an RID
- /// (relative identifier).
- /// </summary>
- /// <remarks>
- /// Construct a SID from a domain SID and an RID
- /// (relative identifier). For example, a domain SID
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252</tt> and RID <tt>1029</tt> would
- /// yield the SID <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
- /// </remarks>
- public Sid(Sid domsid, int rid)
- {
- Revision = domsid.Revision;
- IdentifierAuthority = domsid.IdentifierAuthority;
- SubAuthorityCount = unchecked((byte)(domsid.SubAuthorityCount + 1));
- SubAuthority = new int[SubAuthorityCount];
- int i;
- for (i = 0; i < domsid.SubAuthorityCount; i++)
- {
- SubAuthority[i] = domsid.SubAuthority[i];
- }
- SubAuthority[i] = rid;
- }
-
- public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority
- )
- {
- Revision = sid.Revision;
- SubAuthorityCount = sid.SubAuthorityCount;
- IdentifierAuthority = sid.IdentifierAuthority;
- SubAuthority = sid.SubAuthority;
- this.Type = type;
- this.DomainName = domainName;
- this.AcctName = acctName;
- if (decrementAuthority)
- {
- SubAuthorityCount--;
- SubAuthority = new int[SubAuthorityCount];
- for (int i = 0; i < SubAuthorityCount; i++)
- {
- SubAuthority[i] = sid.SubAuthority[i];
- }
- }
- }
-
- public virtual Sid GetDomainSid()
- {
- return new Sid(this, SidTypeDomain, DomainName, null, GetType()
- != SidTypeDomain);
- }
-
- public virtual int GetRid()
- {
- if (GetType() == SidTypeDomain)
- {
- throw new ArgumentException("This SID is a domain sid");
- }
- return SubAuthority[SubAuthorityCount - 1];
- }
-
- /// <summary>Returns the type of this SID indicating the state or type of account.</summary>
- /// <remarks>
- /// Returns the type of this SID indicating the state or type of account.
- /// <p>
- /// SID types are described in the following table.
- /// <tt>
- /// <table>
- /// <tr><th>Type</th><th>Name</th></tr>
- /// <tr><td>SID_TYPE_USE_NONE</td><td>0</td></tr>
- /// <tr><td>SID_TYPE_USER</td><td>User</td></tr>
- /// <tr><td>SID_TYPE_DOM_GRP</td><td>Domain group</td></tr>
- /// <tr><td>SID_TYPE_DOMAIN</td><td>Domain</td></tr>
- /// <tr><td>SID_TYPE_ALIAS</td><td>Local group</td></tr>
- /// <tr><td>SID_TYPE_WKN_GRP</td><td>Builtin group</td></tr>
- /// <tr><td>SID_TYPE_DELETED</td><td>Deleted</td></tr>
- /// <tr><td>SID_TYPE_INVALID</td><td>Invalid</td></tr>
- /// <tr><td>SID_TYPE_UNKNOWN</td><td>Unknown</td></tr>
- /// </table>
- /// </tt>
- /// </remarks>
- public virtual int GetType()
- {
- if (OriginServer != null)
- {
- ResolveWeak();
- }
- return Type;
- }
-
- /// <summary>
- /// Return text represeting the SID type suitable for display to
- /// users.
- /// </summary>
- /// <remarks>
- /// Return text represeting the SID type suitable for display to
- /// users. Text includes 'User', 'Domain group', 'Local group', etc.
- /// </remarks>
- public virtual string GetTypeText()
- {
- if (OriginServer != null)
- {
- ResolveWeak();
- }
- return SidTypeNames[Type];
- }
-
- /// <summary>
- /// Return the domain name of this SID unless it could not be
- /// resolved in which case the numeric representation is returned.
- /// </summary>
- /// <remarks>
- /// Return the domain name of this SID unless it could not be
- /// resolved in which case the numeric representation is returned.
- /// </remarks>
- public virtual string GetDomainName()
- {
- if (OriginServer != null)
- {
- ResolveWeak();
- }
- if (Type == SidTypeUnknown)
- {
- string full = ToString();
- return Runtime.Substring(full, 0, full.Length - GetAccountName().Length -
- 1);
- }
- return DomainName;
- }
-
- /// <summary>
- /// Return the sAMAccountName of this SID unless it could not
- /// be resolved in which case the numeric RID is returned.
- /// </summary>
- /// <remarks>
- /// Return the sAMAccountName of this SID unless it could not
- /// be resolved in which case the numeric RID is returned. If this
- /// SID is a domain SID, this method will return an empty String.
- /// </remarks>
- public virtual string GetAccountName()
- {
- if (OriginServer != null)
- {
- ResolveWeak();
- }
- if (Type == SidTypeUnknown)
- {
- return string.Empty + SubAuthority[SubAuthorityCount - 1];
- }
- if (Type == SidTypeDomain)
- {
- return string.Empty;
- }
- return AcctName;
- }
-
- public override int GetHashCode()
- {
- int hcode = IdentifierAuthority[5];
- for (int i = 0; i < SubAuthorityCount; i++)
- {
- hcode += 65599 * SubAuthority[i];
- }
- return hcode;
- }
-
- public override bool Equals(object obj)
- {
- if (obj is Sid)
- {
- Sid sid = (Sid)obj;
- if (sid == this)
- {
- return true;
- }
- if (sid.SubAuthorityCount == SubAuthorityCount)
- {
- int i = SubAuthorityCount;
- while (i-- > 0)
- {
- if (sid.SubAuthority[i] != SubAuthority[i])
- {
- return false;
- }
- }
- for (i = 0; i < 6; i++)
- {
- if (sid.IdentifierAuthority[i] != IdentifierAuthority[i])
- {
- return false;
- }
- }
- return sid.Revision == Revision;
- }
- }
- return false;
- }
-
- /// <summary>
- /// Return the numeric representation of this sid such as
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
- /// </summary>
- /// <remarks>
- /// Return the numeric representation of this sid such as
- /// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
- /// </remarks>
- public override string ToString()
- {
- string ret = "S-" + (Revision & unchecked(0xFF)) + "-";
- if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked(
- 0))
- {
- ret += "0x";
- ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
- }
- else
- {
- int shift = 0;
- long id = 0;
- for (int i = 5; i > 1; i--)
- {
- id += (IdentifierAuthority[i] & unchecked(0xFFL)) << shift;
- shift += 8;
- }
- ret += id;
- }
- for (int i1 = 0; i1 < SubAuthorityCount; i1++)
- {
- ret += "-" + (SubAuthority[i1] & unchecked(0xFFFFFFFFL));
- }
- return ret;
- }
-
- /// <summary>
- /// Return a String representing this SID ideal for display to
- /// users.
- /// </summary>
- /// <remarks>
- /// Return a String representing this SID ideal for display to
- /// users. This method should return the same text that the ACL
- /// editor in Windows would display.
- /// <p>
- /// Specifically, if the SID has
- /// been resolved and it is not a domain SID or builtin account,
- /// the full DOMAIN\name form of the account will be
- /// returned (e.g. MYDOM\alice or MYDOM\Domain Users).
- /// If the SID has been resolved but it is is a domain SID,
- /// only the domain name will be returned (e.g. MYDOM).
- /// If the SID has been resolved but it is a builtin account,
- /// only the name component will be returned (e.g. SYSTEM).
- /// If the sid cannot be resolved the numeric representation from
- /// toString() is returned.
- /// </remarks>
- public virtual string ToDisplayString()
- {
- if (OriginServer != null)
- {
- ResolveWeak();
- }
- if (DomainName != null)
- {
- string str;
- if (Type == SidTypeDomain)
- {
- str = DomainName;
- }
- else
- {
- if (Type == SidTypeWknGrp || DomainName.Equals("BUILTIN"))
- {
- if (Type == SidTypeUnknown)
- {
- str = ToString();
- }
- else
- {
- str = AcctName;
- }
- }
- else
- {
- str = DomainName + "\\" + AcctName;
- }
- }
- return str;
- }
- return ToString();
- }
-
- /// <summary>Manually resolve this SID.</summary>
- /// <remarks>
- /// Manually resolve this SID. Normally SIDs are automatically
- /// resolved. However, if a SID is constructed explicitly using a SID
- /// constructor, JCIFS will have no knowledge of the server that created the
- /// SID and therefore cannot possibly resolve it automatically. In this case,
- /// this method will be necessary.
- /// </remarks>
- /// <param name="authorityServerName">The FQDN of the server that is an authority for the SID.
- /// </param>
- /// <param name="auth">Credentials suitable for accessing the SID's information.</param>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication
- auth)
- {
- Sid[] sids = new Sid[1];
- sids[0] = this;
- ResolveSids(authorityServerName, auth, sids);
- }
-
- internal virtual void ResolveWeak()
- {
- if (OriginServer != null)
- {
- try
- {
- Resolve(OriginServer, OriginAuth);
- }
- catch (IOException)
- {
- }
- finally
- {
- OriginServer = null;
- OriginAuth = null;
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle
- domainHandle, Sid domsid, int rid, int flags)
- {
- SamrAliasHandle aliasHandle = null;
- Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
- MsrpcGetMembersInAlias rpc = null;
- try
- {
- aliasHandle = new SamrAliasHandle(handle, domainHandle, unchecked(0x0002000c), rid);
- rpc = new MsrpcGetMembersInAlias(aliasHandle, sidarray);
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- Sid[] sids = new Sid[rpc.Sids.NumSids];
- string originServer = handle.GetServer();
- NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal
- ();
- for (int i = 0; i < sids.Length; i++)
- {
- sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false);
- sids[i].OriginServer = originServer;
- sids[i].OriginAuth = originAuth;
- }
- if (sids.Length > 0 && (flags & SidFlagResolveSids) != 0)
- {
- ResolveSids(originServer, originAuth, sids);
- }
- return sids;
- }
- finally
- {
- if (aliasHandle != null)
- {
- aliasHandle.Close();
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication
- auth, int flags)
- {
- if (Type != SidTypeDomGrp && Type != SidTypeAlias)
- {
- return new Sid[0];
- }
- DcerpcHandle handle = null;
- SamrPolicyHandle policyHandle = null;
- SamrDomainHandle domainHandle = null;
- Sid domsid = GetDomainSid();
- lock (SidCache)
- {
- try
- {
- handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
- , auth);
- policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030));
- domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid);
- return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(),
- flags);
- }
- finally
- {
- if (handle != null)
- {
- if (policyHandle != null)
- {
- if (domainHandle != null)
- {
- domainHandle.Close();
- }
- policyHandle.Close();
- }
- handle.Close();
- }
- }
- }
- }
-
- /// <summary>
- /// This specialized method returns a Map of users and local groups for the
- /// target server where keys are SIDs representing an account and each value
- /// is an List<object> of SIDs represents the local groups that the account is
- /// a member of.
- /// </summary>
- /// <remarks>
- /// This specialized method returns a Map of users and local groups for the
- /// target server where keys are SIDs representing an account and each value
- /// is an List<object> of SIDs represents the local groups that the account is
- /// a member of.
- /// <p/>
- /// This method is designed to assist with computing access control for a
- /// given user when the target object's ACL has local groups. Local groups
- /// are not listed in a user's group membership (e.g. as represented by the
- /// tokenGroups constructed attribute retrived via LDAP).
- /// <p/>
- /// Domain groups nested inside a local group are currently not expanded. In
- /// this case the key (SID) type will be SID_TYPE_DOM_GRP rather than
- /// SID_TYPE_USER.
- /// </remarks>
- /// <param name="authorityServerName">The server from which the local groups will be queried.
- /// </param>
- /// <param name="auth">The credentials required to query groups and group members.</param>
- /// <param name="flags">
- /// Flags that control the behavior of the operation. When all
- /// name associated with SIDs will be required, the SID_FLAG_RESOLVE_SIDS
- /// flag should be used which causes all group member SIDs to be resolved
- /// together in a single more efficient operation.
- /// </param>
- /// <exception cref="System.IO.IOException"></exception>
- internal static Hashtable GetLocalGroupsMap(string authorityServerName, NtlmPasswordAuthentication
- auth, int flags)
- {
- Sid domsid = GetServerSid(authorityServerName, auth);
- DcerpcHandle handle = null;
- SamrPolicyHandle policyHandle = null;
- SamrDomainHandle domainHandle = null;
- Samr.SamrSamArray sam = new Samr.SamrSamArray();
- MsrpcEnumerateAliasesInDomain rpc;
- lock (SidCache)
- {
- try
- {
- handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
- , auth);
- policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000));
- domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid);
- rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam
- );
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, false);
- }
- Hashtable map = new Hashtable();
- for (int ei = 0; ei < rpc.Sam.Count; ei++)
- {
- Samr.SamrSamEntry entry = rpc.Sam.Entries[ei];
- Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid
- , entry.Idx, flags);
- Sid groupSid = new Sid(domsid, entry.Idx);
- groupSid.Type = SidTypeAlias;
- groupSid.DomainName = domsid.GetDomainName();
- groupSid.AcctName = (new UnicodeString(entry.Name, false)).ToString();
- for (int mi = 0; mi < mems.Length; mi++)
- {
- List<object> groups = (List<object>)map.Get(mems[mi]);
- if (groups == null)
- {
- groups = new List<object>();
- map.Put(mems[mi], groups);
- }
- if (!groups.Contains(groupSid))
- {
- groups.Add(groupSid);
- }
- }
- }
- return map;
- }
- finally
- {
- if (handle != null)
- {
- if (policyHandle != null)
- {
- if (domainHandle != null)
- {
- domainHandle.Close();
- }
- policyHandle.Close();
- }
- handle.Close();
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs
deleted file mode 100644
index 8a424a019..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-
-namespace SharpCifs.Smb
-{
- public class SecurityDescriptor
- {
- public int Type;
-
- public Ace[] Aces;
-
- public SecurityDescriptor()
- {
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public SecurityDescriptor(byte[] buffer, int bufferIndex, int len)
- {
- Decode(buffer, bufferIndex, len);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual int Decode(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- bufferIndex++;
- // revision
- bufferIndex++;
- Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- ServerMessageBlock.ReadInt4(buffer, bufferIndex);
- // offset to owner sid
- bufferIndex += 4;
- ServerMessageBlock.ReadInt4(buffer, bufferIndex);
- // offset to group sid
- bufferIndex += 4;
- ServerMessageBlock.ReadInt4(buffer, bufferIndex);
- // offset to sacl
- bufferIndex += 4;
- int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
- bufferIndex = start + daclOffset;
- bufferIndex++;
- // revision
- bufferIndex++;
- int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- if (numAces > 4096)
- {
- throw new IOException("Invalid SecurityDescriptor");
- }
- if (daclOffset != 0)
- {
- Aces = new Ace[numAces];
- for (int i = 0; i < numAces; i++)
- {
- Aces[i] = new Ace();
- bufferIndex += Aces[i].Decode(buffer, bufferIndex);
- }
- }
- else
- {
- Aces = null;
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- string ret = "SecurityDescriptor:\n";
- if (Aces != null)
- {
- for (int ai = 0; ai < Aces.Length; ai++)
- {
- ret += Aces[ai] + "\n";
- }
- }
- else
- {
- ret += "NULL";
- }
- return ret;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs
deleted file mode 100644
index cb38c89fa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs
+++ /dev/null
@@ -1,692 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-using SharpCifs.Util.Transport;
-
-namespace SharpCifs.Smb
-{
- public abstract class ServerMessageBlock: Response
- {
- internal static LogStream Log = LogStream.GetInstance();
-
- internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks;
-
- internal static readonly byte[] Header = { 0xFF, (byte)('S'), (byte)('M'),
- (byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
- internal static void WriteInt2(long val, byte[] dst, int dstIndex)
- {
- dst[dstIndex] = unchecked((byte)(val));
- dst[++dstIndex] = unchecked((byte)(val >> 8));
- }
-
- internal static void WriteInt4(long val, byte[] dst, int dstIndex)
- {
- dst[dstIndex] = unchecked((byte)(val));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >> 8));
- }
-
- internal static int ReadInt2(byte[] src, int srcIndex)
- {
- return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8);
- }
-
- internal static int ReadInt4(byte[] src, int srcIndex)
- {
- return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2]
- & 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24);
- }
-
- internal static long ReadInt8(byte[] src, int srcIndex)
- {
- return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4
- (src, srcIndex + 4)) << 32);
- }
-
- internal static void WriteInt8(long val, byte[] dst, int dstIndex)
- {
- dst[dstIndex] = unchecked((byte)(val));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >>= 8));
- dst[++dstIndex] = unchecked((byte)(val >> 8));
- }
-
- internal static long ReadTime(byte[] src, int srcIndex)
- {
- int low = ReadInt4(src, srcIndex);
- int hi = ReadInt4(src, srcIndex + 4);
- long t = ((long)hi << (int)32L) | (low & unchecked((long)(0xFFFFFFFFL)));
- t = (t / 10000L - SmbConstants.MillisecondsBetween1970And1601);
- return t;
- }
-
- internal static void WriteTime(long t, byte[] dst, int dstIndex)
- {
- if (t != 0L)
- {
- t = (t + SmbConstants.MillisecondsBetween1970And1601) * 10000L;
- }
- WriteInt8(t, dst, dstIndex);
- }
-
- internal static long ReadUTime(byte[] buffer, int bufferIndex)
- {
- return ReadInt4(buffer, bufferIndex) * 1000L;
- }
-
- internal static void WriteUTime(long t, byte[] dst, int dstIndex)
- {
- if (t == 0L || t == unchecked((long)(0xFFFFFFFFFFFFFFFFL)))
- {
- WriteInt4(unchecked((int)(0xFFFFFFFF)), dst, dstIndex);
- return;
- }
- // t isn't in DST either
- WriteInt4((int)(t / 1000L), dst, dstIndex);
- }
-
- internal const byte SmbComCreateDirectory = 0x00;
-
- internal const byte SmbComDeleteDirectory = 0x01;
-
- internal const byte SmbComClose = 0x04;
-
- internal const byte SmbComDelete = 0x06;
-
- internal const byte SmbComRename = 0x07;
-
- internal const byte SmbComQueryInformation = 0x08;
-
- internal const byte SmbComWrite = 0x0B;
-
- internal const byte SmbComCheckDirectory = 0x10;
-
- internal const byte SmbComTransaction = 0x25;
-
- internal const byte SmbComTransactionSecondary = 0x26;
-
- internal const byte SmbComMove = 0x2A;
-
- internal const byte SmbComEcho = 0x2B;
-
- internal const byte SmbComOpenAndx = 0x2D;
-
- internal const byte SmbComReadAndx = 0x2E;
-
- internal const byte SmbComWriteAndx = 0x2F;
-
- internal const byte SmbComTransaction2 = 0x32;
-
- internal const byte SmbComFindClose2 = 0x34;
-
- internal const byte SmbComTreeDisconnect = 0x71;
-
- internal const byte SmbComNegotiate = 0x72;
-
- internal const byte SmbComSessionSetupAndx = 0x73;
-
- internal const byte SmbComLogoffAndx = 0x74;
-
- internal const byte SmbComTreeConnectAndx = 0x75;
-
- internal const byte SmbComNtTransact = 0xA0;
-
- internal const byte SmbComNtTransactSecondary = 0xA1;
-
- internal const byte SmbComNtCreateAndx = 0xA2;
-
- internal byte Command;
-
- internal byte Flags;
-
- internal int HeaderStart;
-
- internal int Length;
-
- internal int BatchLevel;
-
- internal int ErrorCode;
-
- internal int Flags2;
-
- internal int Tid;
-
- internal int Pid;
-
- internal int Uid;
-
- internal int Mid;
-
- internal int WordCount;
-
- internal int ByteCount;
-
- internal bool UseUnicode;
-
- internal bool Received;
-
- internal bool ExtendedSecurity;
-
- internal long ResponseTimeout = 1;
-
- internal int SignSeq;
-
- internal bool VerifyFailed;
-
- internal NtlmPasswordAuthentication Auth = null;
-
- internal string Path;
-
- internal SigningDigest Digest;
-
- internal ServerMessageBlock Response;
-
- public ServerMessageBlock()
- {
- Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
- ));
- Pid = SmbConstants.Pid;
- BatchLevel = 0;
- }
-
- internal virtual void Reset()
- {
- Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
- ));
- Flags2 = 0;
- ErrorCode = 0;
- Received = false;
- Digest = null;
- }
-
- internal virtual int WriteString(string str, byte[] dst, int dstIndex)
- {
- return WriteString(str, dst, dstIndex, UseUnicode);
- }
-
- internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode
- )
- {
- int start = dstIndex;
- try
- {
- if (useUnicode)
- {
- // Unicode requires word alignment
- if (((dstIndex - HeaderStart) % 2) != 0)
- {
- dst[dstIndex++] = (byte)('\0');
- }
- Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex
- , str.Length * 2);
- dstIndex += str.Length * 2;
- dst[dstIndex++] = (byte)('\0');
- dst[dstIndex++] = (byte)('\0');
- }
- else
- {
- byte[] b = Runtime.GetBytesForString(str, SmbConstants.OemEncoding);
- Array.Copy(b, 0, dst, dstIndex, b.Length);
- dstIndex += b.Length;
- dst[dstIndex++] = (byte)('\0');
- }
- }
- catch (UnsupportedEncodingException uee)
- {
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(uee, Log);
- }
- }
- return dstIndex - start;
- }
-
- internal virtual string ReadString(byte[] src, int srcIndex)
- {
- return ReadString(src, srcIndex, 256, UseUnicode);
- }
-
- internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode
- )
- {
- int len = 0;
- string str = null;
- try
- {
- if (useUnicode)
- {
- // Unicode requires word alignment
- if (((srcIndex - HeaderStart) % 2) != 0)
- {
- srcIndex++;
- }
- while (src[srcIndex + len] != 0x00 || src[srcIndex
- + len + 1] != 0x00)
- {
- len += 2;
- if (len > maxLen)
- {
- if (Log.Level > 0)
- {
- Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
- 128);
- }
- throw new RuntimeException("zero termination not found");
- }
- }
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
- }
- else
- {
- while (src[srcIndex + len] != 0x00)
- {
- len++;
- if (len > maxLen)
- {
- if (Log.Level > 0)
- {
- Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
- 128);
- }
- throw new RuntimeException("zero termination not found");
- }
- }
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
- }
- }
- catch (UnsupportedEncodingException uee)
- {
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(uee, Log);
- }
- }
- return str;
- }
-
- internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen
- , bool useUnicode)
- {
- int len = 0;
- string str = null;
- try
- {
- if (useUnicode)
- {
- // Unicode requires word alignment
- if (((srcIndex - HeaderStart) % 2) != 0)
- {
- srcIndex++;
- }
- for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2)
- {
- if (src[srcIndex + len] == 0x00 && src[srcIndex
- + len + 1] == 0x00)
- {
- break;
- }
- if (len > maxLen)
- {
- if (Log.Level > 0)
- {
- Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
- 128);
- }
- throw new RuntimeException("zero termination not found");
- }
- }
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
- }
- else
- {
- for (len = 0; srcIndex < srcEnd; len++)
- {
- if (src[srcIndex + len] == 0x00)
- {
- break;
- }
- if (len > maxLen)
- {
- if (Log.Level > 0)
- {
- Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
- 128);
- }
- throw new RuntimeException("zero termination not found");
- }
- }
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
- }
- }
- catch (UnsupportedEncodingException uee)
- {
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(uee, Log);
- }
- }
- return str;
- }
-
- internal virtual int StringWireLength(string str, int offset)
- {
- int len = str.Length + 1;
- if (UseUnicode)
- {
- len = str.Length * 2 + 2;
- len = (offset % 2) != 0 ? len + 1 : len;
- }
- return len;
- }
-
- internal virtual int ReadStringLength(byte[] src, int srcIndex, int max)
- {
- int len = 0;
- while (src[srcIndex + len] != 0x00)
- {
- if (len++ > max)
- {
- throw new RuntimeException("zero termination not found: " + this);
- }
- }
- return len;
- }
-
- internal virtual int Encode(byte[] dst, int dstIndex)
- {
- int start = HeaderStart = dstIndex;
- dstIndex += WriteHeaderWireFormat(dst, dstIndex);
- WordCount = WriteParameterWordsWireFormat(dst, dstIndex + 1);
- dst[dstIndex++] = unchecked((byte)((WordCount / 2) & 0xFF));
- dstIndex += WordCount;
- WordCount /= 2;
- ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
- dst[dstIndex++] = unchecked((byte)(ByteCount & 0xFF));
- dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & 0xFF));
- dstIndex += ByteCount;
- Length = dstIndex - start;
- if (Digest != null)
- {
- Digest.Sign(dst, HeaderStart, Length, this, Response);
- }
- return Length;
- }
-
- internal virtual int Decode(byte[] buffer, int bufferIndex)
- {
- int start = HeaderStart = bufferIndex;
- bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
- WordCount = buffer[bufferIndex++];
- if (WordCount != 0)
- {
- int n;
- if ((n = ReadParameterWordsWireFormat(buffer, bufferIndex)) != WordCount * 2)
- {
- if (Log.Level >= 5)
- {
- Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned "
- + n);
- }
- }
- bufferIndex += WordCount * 2;
- }
- ByteCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if (ByteCount != 0)
- {
- int n;
- if ((n = ReadBytesWireFormat(buffer, bufferIndex)) != ByteCount)
- {
- if (Log.Level >= 5)
- {
- Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n
- );
- }
- }
- // Don't think we can rely on n being correct here. Must use byteCount.
- // Last paragraph of section 3.13.3 eludes to this.
- bufferIndex += ByteCount;
- }
- Length = bufferIndex - start;
- return Length;
- }
-
- internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
- {
- Array.Copy(Header, 0, dst, dstIndex, Header.Length);
- dst[dstIndex + SmbConstants.CmdOffset] = Command;
- dst[dstIndex + SmbConstants.FlagsOffset] = Flags;
- WriteInt2(Flags2, dst, dstIndex + SmbConstants.FlagsOffset + 1);
- dstIndex += SmbConstants.TidOffset;
- WriteInt2(Tid, dst, dstIndex);
- WriteInt2(Pid, dst, dstIndex + 2);
- WriteInt2(Uid, dst, dstIndex + 4);
- WriteInt2(Mid, dst, dstIndex + 6);
- return SmbConstants.HeaderLength;
- }
-
- internal virtual int ReadHeaderWireFormat(byte[] buffer, int bufferIndex)
- {
- Command = buffer[bufferIndex + SmbConstants.CmdOffset];
- ErrorCode = ReadInt4(buffer, bufferIndex + SmbConstants.ErrorCodeOffset);
- Flags = buffer[bufferIndex + SmbConstants.FlagsOffset];
- Flags2 = ReadInt2(buffer, bufferIndex + SmbConstants.FlagsOffset + 1);
- Tid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset);
- Pid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 2);
- Uid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 4);
- Mid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 6);
- return SmbConstants.HeaderLength;
- }
-
- internal virtual bool IsResponse()
- {
- return (Flags & SmbConstants.FlagsResponse) == SmbConstants.FlagsResponse;
- }
-
- internal abstract int WriteParameterWordsWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- );
-
- internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex);
-
- public override int GetHashCode()
- {
- return Mid;
- }
-
- public override bool Equals(object obj)
- {
- return obj is ServerMessageBlock && ((ServerMessageBlock)obj)
- .Mid == Mid;
- }
-
- public override string ToString()
- {
- string c;
- switch (Command)
- {
- case SmbComNegotiate:
- {
- c = "SMB_COM_NEGOTIATE";
- break;
- }
-
- case SmbComSessionSetupAndx:
- {
- c = "SMB_COM_SESSION_SETUP_ANDX";
- break;
- }
-
- case SmbComTreeConnectAndx:
- {
- c = "SMB_COM_TREE_CONNECT_ANDX";
- break;
- }
-
- case SmbComQueryInformation:
- {
- c = "SMB_COM_QUERY_INFORMATION";
- break;
- }
-
- case SmbComCheckDirectory:
- {
- c = "SMB_COM_CHECK_DIRECTORY";
- break;
- }
-
- case SmbComTransaction:
- {
- c = "SMB_COM_TRANSACTION";
- break;
- }
-
- case SmbComTransaction2:
- {
- c = "SMB_COM_TRANSACTION2";
- break;
- }
-
- case SmbComTransactionSecondary:
- {
- c = "SMB_COM_TRANSACTION_SECONDARY";
- break;
- }
-
- case SmbComFindClose2:
- {
- c = "SMB_COM_FIND_CLOSE2";
- break;
- }
-
- case SmbComTreeDisconnect:
- {
- c = "SMB_COM_TREE_DISCONNECT";
- break;
- }
-
- case SmbComLogoffAndx:
- {
- c = "SMB_COM_LOGOFF_ANDX";
- break;
- }
-
- case SmbComEcho:
- {
- c = "SMB_COM_ECHO";
- break;
- }
-
- case SmbComMove:
- {
- c = "SMB_COM_MOVE";
- break;
- }
-
- case SmbComRename:
- {
- c = "SMB_COM_RENAME";
- break;
- }
-
- case SmbComDelete:
- {
- c = "SMB_COM_DELETE";
- break;
- }
-
- case SmbComDeleteDirectory:
- {
- c = "SMB_COM_DELETE_DIRECTORY";
- break;
- }
-
- case SmbComNtCreateAndx:
- {
- c = "SMB_COM_NT_CREATE_ANDX";
- break;
- }
-
- case SmbComOpenAndx:
- {
- c = "SMB_COM_OPEN_ANDX";
- break;
- }
-
- case SmbComReadAndx:
- {
- c = "SMB_COM_READ_ANDX";
- break;
- }
-
- case SmbComClose:
- {
- c = "SMB_COM_CLOSE";
- break;
- }
-
- case SmbComWriteAndx:
- {
- c = "SMB_COM_WRITE_ANDX";
- break;
- }
-
- case SmbComCreateDirectory:
- {
- c = "SMB_COM_CREATE_DIRECTORY";
- break;
- }
-
- case SmbComNtTransact:
- {
- c = "SMB_COM_NT_TRANSACT";
- break;
- }
-
- case SmbComNtTransactSecondary:
- {
- c = "SMB_COM_NT_TRANSACT_SECONDARY";
- break;
- }
-
- default:
- {
- c = "UNKNOWN";
- break;
- }
- }
- string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode);
- return "command=" + c + ",received=" + Received + ",errorCode=" + str
- + ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x"
- + Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid="
- + Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount="
- + ByteCount;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs
deleted file mode 100644
index 9f57e887b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs
+++ /dev/null
@@ -1,257 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>To filter 0 len updates and for debugging</summary>
- public class SigningDigest
- {
- internal static LogStream Log = LogStream.GetInstance();
-
- private MessageDigest _digest;
-
- private byte[] _macSigningKey;
-
- private bool _bypass;
-
- private int _updates;
-
- private int _signSequence;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public SigningDigest(byte[] macSigningKey, bool bypass)
- {
- try
- {
- _digest = MessageDigest.GetInstance("MD5");
- }
- catch (NoSuchAlgorithmException ex)
- {
- if (Log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, Log);
- }
- throw new SmbException("MD5", ex);
- }
- this._macSigningKey = macSigningKey;
- this._bypass = bypass;
- _updates = 0;
- _signSequence = 0;
- if (Log.Level >= 5)
- {
- Log.WriteLine("macSigningKey:");
- Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length);
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth)
- {
- try
- {
- _digest = MessageDigest.GetInstance("MD5");
- }
- catch (NoSuchAlgorithmException ex)
- {
- if (Log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, Log);
- }
- throw new SmbException("MD5", ex);
- }
- try
- {
- switch (SmbConstants.LmCompatibility)
- {
- case 0:
- case 1:
- case 2:
- {
- _macSigningKey = new byte[40];
- auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
- Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
- , 16, 24);
- break;
- }
-
- case 3:
- case 4:
- case 5:
- {
- _macSigningKey = new byte[16];
- auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
- break;
- }
-
- default:
- {
- _macSigningKey = new byte[40];
- auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
- Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
- , 16, 24);
- break;
- }
- }
- }
- catch (Exception ex)
- {
- throw new SmbException(string.Empty, ex);
- }
- if (Log.Level >= 5)
- {
- Log.WriteLine("LM_COMPATIBILITY=" + SmbConstants.LmCompatibility);
- Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length);
- }
- }
-
- public virtual void Update(byte[] input, int offset, int len)
- {
- if (Log.Level >= 5)
- {
- Log.WriteLine("update: " + _updates + " " + offset + ":" + len);
- Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256));
- Log.Flush();
- }
- if (len == 0)
- {
- return;
- }
- _digest.Update(input, offset, len);
- _updates++;
- }
-
- public virtual byte[] Digest()
- {
- byte[] b;
- b = _digest.Digest();
- if (Log.Level >= 5)
- {
- Log.WriteLine("digest: ");
- Hexdump.ToHexdump(Log, b, 0, b.Length);
- Log.Flush();
- }
- _updates = 0;
- return b;
- }
-
- /// <summary>Performs MAC signing of the SMB.</summary>
- /// <remarks>
- /// Performs MAC signing of the SMB. This is done as follows.
- /// The signature field of the SMB is overwritted with the sequence number;
- /// The MD5 digest of the MAC signing key + the entire SMB is taken;
- /// The first 8 bytes of this are placed in the signature field.
- /// </remarks>
- /// <param name="data">The data.</param>
- /// <param name="offset">The starting offset at which the SMB header begins.</param>
- /// <param name="length">The length of the SMB data starting at offset.</param>
- internal virtual void Sign(byte[] data, int offset, int length, ServerMessageBlock
- request, ServerMessageBlock response)
- {
- request.SignSeq = _signSequence;
- if (response != null)
- {
- response.SignSeq = _signSequence + 1;
- response.VerifyFailed = false;
- }
- try
- {
- Update(_macSigningKey, 0, _macSigningKey.Length);
- int index = offset + SmbConstants.SignatureOffset;
- for (int i = 0; i < 8; i++)
- {
- data[index + i] = 0;
- }
- ServerMessageBlock.WriteInt4(_signSequence, data, index);
- Update(data, offset, length);
- Array.Copy(Digest(), 0, data, index, 8);
- if (_bypass)
- {
- _bypass = false;
- Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index,
- 8);
- }
- }
- catch (Exception ex)
- {
- if (Log.Level > 0)
- {
- Runtime.PrintStackTrace(ex, Log);
- }
- }
- finally
- {
- _signSequence += 2;
- }
- }
-
- /// <summary>Performs MAC signature verification.</summary>
- /// <remarks>
- /// Performs MAC signature verification. This calculates the signature
- /// of the SMB and compares it to the signature field on the SMB itself.
- /// </remarks>
- /// <param name="data">The data.</param>
- /// <param name="offset">The starting offset at which the SMB header begins.</param>
- /// <param name="length">The length of the SMB data starting at offset.</param>
- internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response
- )
- {
- Update(_macSigningKey, 0, _macSigningKey.Length);
- int index = offset;
- Update(data, index, SmbConstants.SignatureOffset);
- index += SmbConstants.SignatureOffset;
- byte[] sequence = new byte[8];
- ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0);
- Update(sequence, 0, sequence.Length);
- index += 8;
- if (response.Command == ServerMessageBlock.SmbComReadAndx)
- {
- SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
- int length = response.Length - raxr.DataLength;
- Update(data, index, length - SmbConstants.SignatureOffset - 8);
- Update(raxr.B, raxr.Off, raxr.DataLength);
- }
- else
- {
- Update(data, index, response.Length - SmbConstants.SignatureOffset - 8);
- }
- byte[] signature = Digest();
- for (int i = 0; i < 8; i++)
- {
- if (signature[i] != data[offset + SmbConstants.SignatureOffset + i])
- {
- if (Log.Level >= 2)
- {
- Log.WriteLine("signature verification failure");
- Hexdump.ToHexdump(Log, signature, 0, 8);
- Hexdump.ToHexdump(Log, data, offset + SmbConstants.SignatureOffset, 8);
- }
- return response.VerifyFailed = true;
- }
- }
- return response.VerifyFailed = false;
- }
-
- public override string ToString()
- {
- return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString
- (_macSigningKey, 0, _macSigningKey.Length);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs
deleted file mode 100644
index defaea71b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- /// <summary>
- /// The <code>SmbAuthException</code> encapsulates the variety of
- /// authentication related error codes returned by an SMB server.
- /// </summary>
- /// <remarks>
- /// The <code>SmbAuthException</code> encapsulates the variety of
- /// authentication related error codes returned by an SMB server.
- /// <p>
- /// See <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for more information about <code>SmbAuthException</code>.
- /// </remarks>
-
- public class SmbAuthException : SmbException
- {
- internal SmbAuthException(int errcode) : base(errcode, null)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs
deleted file mode 100644
index 2295de5b9..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComBlankResponse : ServerMessageBlock
- {
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComBlankResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs
deleted file mode 100644
index 4a160f518..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComClose : ServerMessageBlock
- {
- private int _fid;
-
- private long _lastWriteTime;
-
- internal SmbComClose(int fid, long lastWriteTime)
- {
- this._fid = fid;
- this._lastWriteTime = lastWriteTime;
- Command = SmbComClose;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- WriteInt2(_fid, dst, dstIndex);
- dstIndex += 2;
- WriteUTime(_lastWriteTime, dst, dstIndex);
- return 6;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComClose[" + base.ToString() + ",fid=" + _fid + ",lastWriteTime="
- + _lastWriteTime + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs
deleted file mode 100644
index 7549db01a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComCreateDirectory : ServerMessageBlock
- {
- internal SmbComCreateDirectory(string directoryName)
- {
- Path = directoryName;
- Command = SmbComCreateDirectory;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = unchecked(unchecked(0x04));
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComCreateDirectory[" + base.ToString() + ",directoryName="
- + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs
deleted file mode 100644
index d055d2446..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComDelete : ServerMessageBlock
- {
- private int _searchAttributes;
-
- internal SmbComDelete(string fileName)
- {
- Path = fileName;
- Command = SmbComDelete;
- _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- WriteInt2(_searchAttributes, dst, dstIndex);
- return 2;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = unchecked(unchecked(0x04));
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComDelete[" + base.ToString() + ",searchAttributes=0x" + Hexdump
- .ToHexString(_searchAttributes, 4) + ",fileName=" + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs
deleted file mode 100644
index 240139a17..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComDeleteDirectory : ServerMessageBlock
- {
- internal SmbComDeleteDirectory(string directoryName)
- {
- Path = directoryName;
- Command = SmbComDeleteDirectory;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = unchecked(unchecked(0x04));
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName="
- + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs
deleted file mode 100644
index 9b7c0c765..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComFindClose2 : ServerMessageBlock
- {
- private int _sid;
-
- internal SmbComFindClose2(int sid)
- {
- this._sid = sid;
- Command = SmbComFindClose2;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- WriteInt2(_sid, dst, dstIndex);
- return 2;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs
deleted file mode 100644
index 8f88ccd57..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComLogoffAndX : AndXServerMessageBlock
- {
- internal SmbComLogoffAndX(ServerMessageBlock andx) : base(andx)
- {
- Command = SmbComLogoffAndx;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComLogoffAndX[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs
deleted file mode 100644
index 26b5ba63a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs
+++ /dev/null
@@ -1,193 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComNtCreateAndX : AndXServerMessageBlock
- {
- internal const int FileSupersede = unchecked(0x0);
-
- internal const int FileOpen = unchecked(0x1);
-
- internal const int FileCreate = unchecked(0x2);
-
- internal const int FileOpenIf = unchecked(0x3);
-
- internal const int FileOverwrite = unchecked(0x4);
-
- internal const int FileOverwriteIf = unchecked(0x5);
-
- internal const int FileWriteThrough = unchecked(0x00000002);
-
- internal const int FileSequentialOnly = unchecked(0x00000004);
-
- internal const int FileSynchronousIoAlert = unchecked(0x00000010);
-
- internal const int FileSynchronousIoNonalert = unchecked(0x00000020);
-
- internal const int SecurityContextTracking = unchecked(0x01);
-
- internal const int SecurityEffectiveOnly = unchecked(0x02);
-
- private int _rootDirectoryFid;
-
- private int _extFileAttributes;
-
- private int _shareAccess;
-
- private int _createDisposition;
-
- private int _createOptions;
-
- private int _impersonationLevel;
-
- private long _allocationSize;
-
- private byte _securityFlags;
-
- private int _namelenIndex;
-
- internal int Flags0;
-
- internal int DesiredAccess;
-
- internal SmbComNtCreateAndX(string name, int flags, int access, int shareAccess,
- int extFileAttributes, int createOptions, ServerMessageBlock andx) : base(andx)
- {
- // share access specified in SmbFile
- // create disposition
- // create options
- // security flags
- Path = name;
- Command = SmbComNtCreateAndx;
- DesiredAccess = access;
- DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes;
- // extFileAttributes
- this._extFileAttributes = extFileAttributes;
- // shareAccess
- this._shareAccess = shareAccess;
- // createDisposition
- if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
- {
- // truncate the file
- if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
- {
- // create it if necessary
- _createDisposition = FileOverwriteIf;
- }
- else
- {
- _createDisposition = FileOverwrite;
- }
- }
- else
- {
- // don't truncate the file
- if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
- {
- // create it if necessary
- if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
- {
- // fail if already exists
- _createDisposition = FileCreate;
- }
- else
- {
- _createDisposition = FileOpenIf;
- }
- }
- else
- {
- _createDisposition = FileOpen;
- }
- }
- if ((createOptions & unchecked(0x0001)) == 0)
- {
- this._createOptions = createOptions | unchecked(0x0040);
- }
- else
- {
- this._createOptions = createOptions;
- }
- _impersonationLevel = unchecked(0x02);
- // As seen on NT :~)
- _securityFlags = unchecked(unchecked(0x03));
- }
-
- // SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // name length without counting null termination
- _namelenIndex = dstIndex;
- dstIndex += 2;
- WriteInt4(Flags0, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(_rootDirectoryFid, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(DesiredAccess, dst, dstIndex);
- dstIndex += 4;
- WriteInt8(_allocationSize, dst, dstIndex);
- dstIndex += 8;
- WriteInt4(_extFileAttributes, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(_shareAccess, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(_createDisposition, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(_createOptions, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(_impersonationLevel, dst, dstIndex);
- dstIndex += 4;
- dst[dstIndex++] = _securityFlags;
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int n;
- n = WriteString(Path, dst, dstIndex);
- WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex);
- return n;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComNTCreateAndX[" + base.ToString() + ",flags=0x" + Hexdump
- .ToHexString(Flags0, 2) + ",rootDirectoryFid=" + _rootDirectoryFid + ",desiredAccess=0x"
- + Hexdump.ToHexString(DesiredAccess, 4) + ",allocationSize=" + _allocationSize +
- ",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) + ",shareAccess=0x"
- + Hexdump.ToHexString(_shareAccess, 4) + ",createDisposition=0x" + Hexdump.ToHexString
- (_createDisposition, 4) + ",createOptions=0x" + Hexdump.ToHexString(_createOptions
- , 8) + ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4) + ",securityFlags=0x"
- + Hexdump.ToHexString(_securityFlags, 2) + ",name=" + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs
deleted file mode 100644
index 4a007bdc5..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock
- {
- internal const int ExclusiveOplockGranted = 1;
-
- internal const int BatchOplockGranted = 2;
-
- internal const int LevelIiOplockGranted = 3;
-
- internal byte OplockLevel;
-
- internal int Fid;
-
- internal int CreateAction;
-
- internal int ExtFileAttributes;
-
- internal int FileType;
-
- internal int DeviceState;
-
- internal long CreationTime;
-
- internal long LastAccessTime;
-
- internal long LastWriteTime;
-
- internal long ChangeTime;
-
- internal long AllocationSize;
-
- internal long EndOfFile;
-
- internal bool Directory;
-
- internal bool IsExtended;
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- OplockLevel = buffer[bufferIndex++];
- Fid = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- CreateAction = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- CreationTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- LastAccessTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- LastWriteTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- ChangeTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- ExtFileAttributes = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- AllocationSize = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- EndOfFile = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- FileType = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DeviceState = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel="
- + OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction
- , 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime="
- + Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate
- (LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x"
- + Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize
- + ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState
- + ",directory=" + Directory + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs
deleted file mode 100644
index 499bffbd9..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComNegotiate : ServerMessageBlock
- {
- private const string Dialects = "\u0002NT LM 0.12\u0000";
-
- public SmbComNegotiate()
- {
- Command = SmbComNegotiate;
- Flags2 = SmbConstants.DefaultFlags2;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- byte[] dialects;
- try
- {
- //dialects = Runtime.GetBytesForString(Dialects, "ASCII");
- dialects = Runtime.GetBytesForString(Dialects, "UTF-8");
- }
- catch (UnsupportedEncodingException)
- {
- return 0;
- }
- Array.Copy(dialects, 0, dst, dstIndex, dialects.Length);
- return dialects.Length;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount
- + ",dialects=NT LM 0.12]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs
deleted file mode 100644
index c4cd1c129..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs
+++ /dev/null
@@ -1,164 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComNegotiateResponse : ServerMessageBlock
- {
- internal int DialectIndex;
-
- internal SmbTransport.ServerData Server;
-
- internal SmbComNegotiateResponse(SmbTransport.ServerData server)
- {
- this.Server = server;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- DialectIndex = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if (DialectIndex > 10)
- {
- return bufferIndex - start;
- }
- Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF);
- Server.Security = Server.SecurityMode & unchecked(0x01);
- Server.EncryptedPasswords = (Server.SecurityMode & unchecked(0x02)) == unchecked(
- 0x02);
- Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked(
- 0x04);
- Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked(
- 0x08);
- Server.MaxMpxCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Server.MaxBufferSize = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- Server.MaxRawSize = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- Server.SessionKey = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- Server.Capabilities = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- Server.ServerTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- Server.ServerTimeZone = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF);
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- int start = bufferIndex;
- if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
- {
- Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
- Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength
- );
- bufferIndex += Server.EncryptionKeyLength;
- if (ByteCount > Server.EncryptionKeyLength)
- {
- int len = 0;
- // TODO: we can use new string routine here
- try
- {
- if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
- {
- while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer
- [bufferIndex + len + 1] != unchecked(unchecked(0x00)))
- {
- len += 2;
- if (len > 256)
- {
- throw new RuntimeException("zero termination not found");
- }
- }
- Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
- , SmbConstants.UniEncoding);
- }
- else
- {
- while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)))
- {
- len++;
- if (len > 256)
- {
- throw new RuntimeException("zero termination not found");
- }
- }
- Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
- , SmbConstants.OemEncoding);
- }
- }
- catch (UnsupportedEncodingException uee)
- {
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(uee, Log);
- }
- }
- bufferIndex += len;
- }
- else
- {
- Server.OemDomainName = "";
- }
- }
- else
- {
- Server.Guid = new byte[16];
- Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16);
- Server.OemDomainName = "";
- }
- // ignore SPNEGO token for now ...
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" +
- WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString
- (Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share"
- : "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount="
- + Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize="
- + Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x"
- + Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString
- (Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server
- .ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength="
- + Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" +
- Server.OemDomainName + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs
deleted file mode 100644
index b5d2cf947..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal abstract class SmbComNtTransaction : SmbComTransaction
- {
- private const int NttPrimarySetupOffset = 69;
-
- private const int NttSecondaryParameterOffset = 51;
-
- internal const int NtTransactQuerySecurityDesc = 6;
-
- internal int Function;
-
- public SmbComNtTransaction()
- {
- // relative to headerStart
- primarySetupOffset = NttPrimarySetupOffset;
- secondaryParameterOffset = NttSecondaryParameterOffset;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- if (Command != SmbComNtTransactSecondary)
- {
- dst[dstIndex++] = MaxSetupCount;
- }
- else
- {
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- // Reserved
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved
- WriteInt4(TotalParameterCount, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(TotalDataCount, dst, dstIndex);
- dstIndex += 4;
- if (Command != SmbComNtTransactSecondary)
- {
- WriteInt4(MaxParameterCount, dst, dstIndex);
- dstIndex += 4;
- WriteInt4(MaxDataCount, dst, dstIndex);
- dstIndex += 4;
- }
- WriteInt4(ParameterCount, dst, dstIndex);
- dstIndex += 4;
- WriteInt4((ParameterCount == 0 ? 0 : ParameterOffset), dst, dstIndex);
- dstIndex += 4;
- if (Command == SmbComNtTransactSecondary)
- {
- WriteInt4(ParameterDisplacement, dst, dstIndex);
- dstIndex += 4;
- }
- WriteInt4(DataCount, dst, dstIndex);
- dstIndex += 4;
- WriteInt4((DataCount == 0 ? 0 : DataOffset), dst, dstIndex);
- dstIndex += 4;
- if (Command == SmbComNtTransactSecondary)
- {
- WriteInt4(DataDisplacement, dst, dstIndex);
- dstIndex += 4;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- else
- {
- // Reserved1
- dst[dstIndex++] = unchecked((byte)SetupCount);
- WriteInt2(Function, dst, dstIndex);
- dstIndex += 2;
- dstIndex += WriteSetupWireFormat(dst, dstIndex);
- }
- return dstIndex - start;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs
deleted file mode 100644
index 88d73528a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse
- {
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- buffer[bufferIndex++] = unchecked(unchecked(0x00));
- // Reserved
- buffer[bufferIndex++] = unchecked(unchecked(0x00));
- // Reserved
- buffer[bufferIndex++] = unchecked(unchecked(0x00));
- // Reserved
- TotalParameterCount = ReadInt4(buffer, bufferIndex);
- if (BufDataStart == 0)
- {
- BufDataStart = TotalParameterCount;
- }
- bufferIndex += 4;
- TotalDataCount = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- ParameterCount = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- ParameterOffset = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- ParameterDisplacement = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- DataCount = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- DataOffset = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- DataDisplacement = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- SetupCount = buffer[bufferIndex] & unchecked(0xFF);
- bufferIndex += 2;
- if (SetupCount != 0)
- {
- if (Log.Level >= 3)
- {
- Log.WriteLine("setupCount is not zero: " + SetupCount);
- }
- }
- return bufferIndex - start;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs
deleted file mode 100644
index de11e2a6a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs
+++ /dev/null
@@ -1,190 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComOpenAndX : AndXServerMessageBlock
- {
- private const int FlagsReturnAdditionalInfo = 0x01;
-
- private const int FlagsRequestOplock = 0x02;
-
- private const int FlagsRequestBatchOplock = 0x04;
-
- private const int SharingCompatibility = 0x00;
-
- private const int SharingDenyReadWriteExecute = 0x10;
-
- private const int SharingDenyWrite = 0x20;
-
- private const int SharingDenyReadExecute = 0x30;
-
- private const int SharingDenyNone = 0x40;
-
- private const int DoNotCache = 0x1000;
-
- private const int WriteThrough = 0x4000;
-
- private const int OpenFnCreate = 0x10;
-
- private const int OpenFnFailIfExists = 0x00;
-
- private const int OpenFnOpen = 0x01;
-
- private const int OpenFnTrunc = 0x02;
-
- private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX"
- , 1);
-
- internal int flags;
-
- internal int DesiredAccess;
-
- internal int SearchAttributes;
-
- internal int FileAttributes;
-
- internal int CreationTime;
-
- internal int OpenFunction;
-
- internal int AllocationSize;
-
- internal SmbComOpenAndX(string fileName, int access, int flags, ServerMessageBlock
- andx) : base(andx)
- {
- // flags (not the same as flags constructor argument)
- // Access Mode Encoding for desiredAccess
- // bit 12
- // bit 14
- // flags is NOT the same as flags member
- Path = fileName;
- Command = SmbComOpenAndx;
- DesiredAccess = access & 0x3;
- if (DesiredAccess == 0x3)
- {
- DesiredAccess = 0x2;
- }
- DesiredAccess |= SharingDenyNone;
- DesiredAccess &= ~0x1;
- // Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
- // searchAttributes
- SearchAttributes = SmbConstants.AttrDirectory | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
- // fileAttributes
- FileAttributes = 0;
- // openFunction
- if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
- {
- // truncate the file
- if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
- {
- // create it if necessary
- OpenFunction = OpenFnTrunc | OpenFnCreate;
- }
- else
- {
- OpenFunction = OpenFnTrunc;
- }
- }
- else
- {
- // don't truncate the file
- if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
- {
- // create it if necessary
- if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
- {
- // fail if already exists
- OpenFunction = OpenFnCreate | OpenFnFailIfExists;
- }
- else
- {
- OpenFunction = OpenFnCreate | OpenFnOpen;
- }
- }
- else
- {
- OpenFunction = OpenFnOpen;
- }
- }
- }
-
- internal override int GetBatchLimit(byte command)
- {
- return command == SmbComReadAndx ? BatchLimit : 0;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(flags, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(DesiredAccess, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(SearchAttributes, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(FileAttributes, dst, dstIndex);
- dstIndex += 2;
- CreationTime = 0;
- WriteInt4(CreationTime, dst, dstIndex);
- dstIndex += 4;
- WriteInt2(OpenFunction, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(AllocationSize, dst, dstIndex);
- dstIndex += 4;
- for (int i = 0; i < 8; i++)
- {
- dst[dstIndex++] = 0x00;
- }
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- if (UseUnicode)
- {
- dst[dstIndex++] = (byte)('\0');
- }
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComOpenAndX[" + base.ToString() + ",flags=0x" + Hexdump.ToHexString
- (flags, 2) + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + ",searchAttributes=0x"
- + Hexdump.ToHexString(SearchAttributes, 4) + ",fileAttributes=0x" + Hexdump.ToHexString
- (FileAttributes, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime
- ) + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2) + ",allocationSize="
- + AllocationSize + ",fileName=" + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs
deleted file mode 100644
index 9c49d19a8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComOpenAndXResponse : AndXServerMessageBlock
- {
- internal int Fid;
-
- internal int FileAttributes;
-
- internal int DataSize;
-
- internal int GrantedAccess;
-
- internal int FileType;
-
- internal int DeviceState;
-
- internal int Action;
-
- internal int ServerFid;
-
- internal long LastWriteTime;
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- Fid = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- FileAttributes = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- LastWriteTime = ReadUTime(buffer, bufferIndex);
- bufferIndex += 4;
- DataSize = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- GrantedAccess = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- FileType = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DeviceState = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Action = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- ServerFid = ReadInt4(buffer, bufferIndex);
- bufferIndex += 6;
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComOpenAndXResponse[" + base.ToString() + ",fid=" + Fid + ",fileAttributes="
- + FileAttributes + ",lastWriteTime=" + LastWriteTime + ",dataSize=" + DataSize
- + ",grantedAccess=" + GrantedAccess + ",fileType=" + FileType + ",deviceState="
- + DeviceState + ",action=" + Action + ",serverFid=" + ServerFid + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs
deleted file mode 100644
index a528dbb11..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComQueryInformation : ServerMessageBlock
- {
- internal SmbComQueryInformation(string filename)
- {
- Path = filename;
- Command = SmbComQueryInformation;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = 0x04;
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComQueryInformation[" + base.ToString() + ",filename=" + Path
- + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs
deleted file mode 100644
index 040f081f0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComQueryInformationResponse : ServerMessageBlock, IInfo
- {
- private int _fileAttributes = 0x0000;
-
- private long _lastWriteTime;
-
- private long _serverTimeZoneOffset;
-
- private int _fileSize;
-
- internal SmbComQueryInformationResponse(long serverTimeZoneOffset)
- {
- this._serverTimeZoneOffset = serverTimeZoneOffset;
- Command = SmbComQueryInformation;
- }
-
- public virtual int GetAttributes()
- {
- return _fileAttributes;
- }
-
- public virtual long GetCreateTime()
- {
- return _lastWriteTime + _serverTimeZoneOffset;
- }
-
- public virtual long GetLastWriteTime()
- {
- return _lastWriteTime + _serverTimeZoneOffset;
- }
-
- public virtual long GetSize()
- {
- return _fileSize;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- if (WordCount == 0)
- {
- return 0;
- }
- _fileAttributes = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _lastWriteTime = ReadUTime(buffer, bufferIndex);
- bufferIndex += 4;
- _fileSize = ReadInt4(buffer, bufferIndex);
- return 20;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComQueryInformationResponse[" + base.ToString() + ",fileAttributes=0x"
- + Hexdump.ToHexString(_fileAttributes, 4) + ",lastWriteTime=" + Extensions.CreateDate
- (_lastWriteTime) + ",fileSize=" + _fileSize + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs
deleted file mode 100644
index e75179700..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComReadAndX : AndXServerMessageBlock
- {
- private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.ReadAndX.Close"
- , 1);
-
- private long _offset;
-
- private int _fid;
-
- private int _openTimeout;
-
- internal int MaxCount;
-
- internal int MinCount;
-
- internal int Remaining;
-
- public SmbComReadAndX() : base(null)
- {
- Command = SmbComReadAndx;
- _openTimeout = unchecked((int)(0xFFFFFFFF));
- }
-
- internal SmbComReadAndX(int fid, long offset, int maxCount, ServerMessageBlock andx
- ) : base(andx)
- {
- this._fid = fid;
- this._offset = offset;
- this.MaxCount = MinCount = maxCount;
- Command = SmbComReadAndx;
- _openTimeout = unchecked((int)(0xFFFFFFFF));
- }
-
- internal virtual void SetParam(int fid, long offset, int maxCount)
- {
- this._fid = fid;
- this._offset = offset;
- this.MaxCount = MinCount = maxCount;
- }
-
- internal override int GetBatchLimit(byte command)
- {
- return command == SmbComClose ? BatchLimit : 0;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_fid, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_offset, dst, dstIndex);
- dstIndex += 4;
- WriteInt2(MaxCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(MinCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_openTimeout, dst, dstIndex);
- dstIndex += 4;
- WriteInt2(Remaining, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_offset >> 32, dst, dstIndex);
- dstIndex += 4;
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComReadAndX[" + base.ToString() + ",fid=" + _fid + ",offset="
- + _offset + ",maxCount=" + MaxCount + ",minCount=" + MinCount + ",openTimeout="
- + _openTimeout + ",remaining=" + Remaining + ",offset=" + _offset + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs
deleted file mode 100644
index 4d857aa2c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComReadAndXResponse : AndXServerMessageBlock
- {
- internal byte[] B;
-
- internal int Off;
-
- internal int DataCompactionMode;
-
- internal int DataLength;
-
- internal int DataOffset;
-
- public SmbComReadAndXResponse()
- {
- }
-
- internal SmbComReadAndXResponse(byte[] b, int off)
- {
- this.B = b;
- this.Off = off;
- }
-
- internal virtual void SetParam(byte[] b, int off)
- {
- this.B = b;
- this.Off = off;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- bufferIndex += 2;
- // reserved
- DataCompactionMode = ReadInt2(buffer, bufferIndex);
- bufferIndex += 4;
- // 2 reserved
- DataLength = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DataOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 12;
- // 10 reserved
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- // handled special in SmbTransport.doRecv()
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComReadAndXResponse[" + base.ToString() + ",dataCompactionMode="
- + DataCompactionMode + ",dataLength=" + DataLength + ",dataOffset=" + DataOffset
- + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs
deleted file mode 100644
index 0ac57dd3e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComRename : ServerMessageBlock
- {
- private int _searchAttributes;
-
- private string _oldFileName;
-
- private string _newFileName;
-
- internal SmbComRename(string oldFileName, string newFileName)
- {
- Command = SmbComRename;
- this._oldFileName = oldFileName;
- this._newFileName = newFileName;
- _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrSystem | SmbConstants.AttrDirectory;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- WriteInt2(_searchAttributes, dst, dstIndex);
- return 2;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = unchecked(unchecked(0x04));
- dstIndex += WriteString(_oldFileName, dst, dstIndex);
- dst[dstIndex++] = unchecked(unchecked(0x04));
- if (UseUnicode)
- {
- dst[dstIndex++] = unchecked((byte)('\0'));
- }
- dstIndex += WriteString(_newFileName, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComRename[" + base.ToString() + ",searchAttributes=0x" + Hexdump
- .ToHexString(_searchAttributes, 4) + ",oldFileName=" + _oldFileName + ",newFileName="
- + _newFileName + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs
deleted file mode 100644
index a1642391c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs
+++ /dev/null
@@ -1,234 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// Ported to C# by J. Arturo <webmaster at komodosoft.net>
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComSessionSetupAndX : AndXServerMessageBlock
- {
- private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX"
- , 1);
-
- private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords"
- , true);
-
- private byte[] _lmHash;
-
- private byte[] _ntHash;
-
- private byte[] _blob;
-
- private int _sessionKey;
-
- private int _capabilities;
-
- private string _accountName;
-
- private string _primaryDomain;
-
- internal SmbSession Session;
-
- internal object Cred;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal SmbComSessionSetupAndX(SmbSession session, ServerMessageBlock andx, object
- cred) : base(andx)
- {
- Command = SmbComSessionSetupAndx;
- this.Session = session;
- this.Cred = cred;
- _sessionKey = session.transport.SessionKey;
- _capabilities = session.transport.Capabilities;
- if (session.transport.Server.Security == SmbConstants.SecurityUser)
- {
- if (cred is NtlmPasswordAuthentication)
- {
- NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred;
- if (auth == NtlmPasswordAuthentication.Anonymous)
- {
- _lmHash = new byte[0];
- _ntHash = new byte[0];
- _capabilities &= ~SmbConstants.CapExtendedSecurity;
- }
- else
- {
- if (session.transport.Server.EncryptedPasswords)
- {
- _lmHash = auth.GetAnsiHash(session.transport.Server.EncryptionKey);
- _ntHash = auth.GetUnicodeHash(session.transport.Server.EncryptionKey);
- // prohibit HTTP auth attempts for the null session
- if (_lmHash.Length == 0 && _ntHash.Length == 0)
- {
- throw new RuntimeException("Null setup prohibited.");
- }
- }
- else
- {
- if (DisablePlainTextPasswords)
- {
- throw new RuntimeException("Plain text passwords are disabled");
- }
- if (UseUnicode)
- {
- // plain text
- string password = auth.GetPassword();
- _lmHash = new byte[0];
- _ntHash = new byte[(password.Length + 1) * 2];
- WriteString(password, _ntHash, 0);
- }
- else
- {
- // plain text
- string password = auth.GetPassword();
- _lmHash = new byte[(password.Length + 1) * 2];
- _ntHash = new byte[0];
- WriteString(password, _lmHash, 0);
- }
- }
- }
- _accountName = auth.Username;
- if (UseUnicode)
- {
- _accountName = _accountName.ToUpper();
- }
- _primaryDomain = auth.Domain.ToUpper();
- }
- else
- {
- if (cred is byte[])
- {
- _blob = (byte[])cred;
- }
- else
- {
- throw new SmbException("Unsupported credential type");
- }
- }
- }
- else
- {
- if (session.transport.Server.Security == SmbConstants.SecurityShare)
- {
- if (cred is NtlmPasswordAuthentication)
- {
- NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred;
- _lmHash = new byte[0];
- _ntHash = new byte[0];
- _accountName = auth.Username;
- if (UseUnicode)
- {
- _accountName = _accountName.ToUpper();
- }
- _primaryDomain = auth.Domain.ToUpper();
- }
- else
- {
- throw new SmbException("Unsupported credential type");
- }
- }
- else
- {
- throw new SmbException("Unsupported");
- }
- }
- }
-
- internal override int GetBatchLimit(byte command)
- {
- return command == SmbComTreeConnectAndx ? BatchLimit : 0;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(Session.transport.SndBufSize, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(Session.transport.MaxMpxCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(SmbConstants.VcNumber, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_sessionKey, dst, dstIndex);
- dstIndex += 4;
- if (_blob != null)
- {
- WriteInt2(_blob.Length, dst, dstIndex);
- dstIndex += 2;
- }
- else
- {
- WriteInt2(_lmHash.Length, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_ntHash.Length, dst, dstIndex);
- dstIndex += 2;
- }
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- WriteInt4(_capabilities, dst, dstIndex);
- dstIndex += 4;
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- if (_blob != null)
- {
- Array.Copy(_blob, 0, dst, dstIndex, _blob.Length);
- dstIndex += _blob.Length;
- }
- else
- {
- Array.Copy(_lmHash, 0, dst, dstIndex, _lmHash.Length);
- dstIndex += _lmHash.Length;
- Array.Copy(_ntHash, 0, dst, dstIndex, _ntHash.Length);
- dstIndex += _ntHash.Length;
- dstIndex += WriteString(_accountName, dst, dstIndex);
- dstIndex += WriteString(_primaryDomain, dst, dstIndex);
- }
- dstIndex += WriteString(SmbConstants.NativeOs, dst, dstIndex);
- dstIndex += WriteString(SmbConstants.NativeLanman, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- string result = "SmbComSessionSetupAndX[" + base.ToString() + ",snd_buf_size="
- + Session.transport.SndBufSize + ",maxMpxCount=" + Session.transport.MaxMpxCount
- + ",VC_NUMBER=" + SmbConstants.VcNumber + ",sessionKey=" + _sessionKey + ",lmHash.length="
- + (_lmHash == null ? 0 : _lmHash.Length) + ",ntHash.length=" + (_ntHash == null ?
- 0 : _ntHash.Length) + ",capabilities=" + _capabilities + ",accountName=" + _accountName
- + ",primaryDomain=" + _primaryDomain + ",NATIVE_OS=" + SmbConstants.NativeOs
- + ",NATIVE_LANMAN=" + SmbConstants.NativeLanman + "]";
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs
deleted file mode 100644
index a3b80a669..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComSessionSetupAndXResponse : AndXServerMessageBlock
- {
- private string _nativeOs = string.Empty;
-
- private string _nativeLanMan = string.Empty;
-
- private string _primaryDomain = string.Empty;
-
- internal bool IsLoggedInAsGuest;
-
- internal byte[] Blob;
-
- internal SmbComSessionSetupAndXResponse(ServerMessageBlock andx) : base(andx)
- {
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- IsLoggedInAsGuest = (buffer[bufferIndex] & 0x01) == 0x01 ? true : false;
- bufferIndex += 2;
- if (ExtendedSecurity)
- {
- int blobLength = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Blob = new byte[blobLength];
- }
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- int start = bufferIndex;
- if (ExtendedSecurity)
- {
- Array.Copy(buffer, bufferIndex, Blob, 0, Blob.Length);
- bufferIndex += Blob.Length;
- }
- _nativeOs = ReadString(buffer, bufferIndex);
- bufferIndex += StringWireLength(_nativeOs, bufferIndex);
- _nativeLanMan = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode
- );
- bufferIndex += StringWireLength(_nativeLanMan, bufferIndex);
- if (!ExtendedSecurity)
- {
- _primaryDomain = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode
- );
- bufferIndex += StringWireLength(_primaryDomain, bufferIndex);
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- string result = "SmbComSessionSetupAndXResponse[" + base.ToString() +
- ",isLoggedInAsGuest=" + IsLoggedInAsGuest + ",nativeOs=" + _nativeOs + ",nativeLanMan="
- + _nativeLanMan + ",primaryDomain=" + _primaryDomain + "]";
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs
deleted file mode 100644
index b3aeaaf7d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs
+++ /dev/null
@@ -1,346 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal abstract class SmbComTransaction : ServerMessageBlock
- {
- private static readonly int DefaultMaxDataCount = Config.GetInt("jcifs.smb.client.transaction_buf_size"
- , TransactionBufSize) - 512;
-
- private const int PrimarySetupOffset = 61;
-
- private const int SecondaryParameterOffset = 51;
-
- private const int DisconnectTid = unchecked(0x01);
-
- private const int OneWayTransaction = unchecked(0x02);
-
- private const int PaddingSize = 2;
-
- private int _flags = unchecked(0x00);
-
- private int _fid;
-
- private int _pad;
-
- private int _pad1;
-
- private bool _hasMore = true;
-
- private bool _isPrimary = true;
-
- private int _bufParameterOffset;
-
- private int _bufDataOffset;
-
- internal const int TransactionBufSize = unchecked(0xFFFF);
-
- internal const byte Trans2FindFirst2 = unchecked(unchecked(0x01));
-
- internal const byte Trans2FindNext2 = unchecked(unchecked(0x02));
-
- internal const byte Trans2QueryFsInformation = unchecked(unchecked(0x03));
-
- internal const byte Trans2QueryPathInformation = unchecked(unchecked(0x05));
-
- internal const byte Trans2GetDfsReferral = unchecked(unchecked(0x10));
-
- internal const byte Trans2SetFileInformation = unchecked(unchecked(0x08));
-
- internal const int NetShareEnum = unchecked(0x0000);
-
- internal const int NetServerEnum2 = unchecked(0x0068);
-
- internal const int NetServerEnum3 = unchecked(0x00D7);
-
- internal const byte TransPeekNamedPipe = unchecked(unchecked(0x23
- ));
-
- internal const byte TransWaitNamedPipe = unchecked(unchecked(0x53
- ));
-
- internal const byte TransCallNamedPipe = unchecked(unchecked(0x54
- ));
-
- internal const byte TransTransactNamedPipe = unchecked(unchecked(0x26));
-
- protected internal int primarySetupOffset;
-
- protected internal int secondaryParameterOffset;
-
- protected internal int ParameterCount;
-
- protected internal int ParameterOffset;
-
- protected internal int ParameterDisplacement;
-
- protected internal int DataCount;
-
- protected internal int DataOffset;
-
- protected internal int DataDisplacement;
-
- internal int TotalParameterCount;
-
- internal int TotalDataCount;
-
- internal int MaxParameterCount;
-
- internal int MaxDataCount = DefaultMaxDataCount;
-
- internal byte MaxSetupCount;
-
- internal int Timeout = 0;
-
- internal int SetupCount = 1;
-
- internal byte SubCommand;
-
- internal string Name = string.Empty;
-
- internal int MaxBufferSize;
-
- internal byte[] TxnBuf;
-
- public SmbComTransaction()
- {
- // relative to headerStart
- // set in SmbTransport.sendTransaction() before nextElement called
- MaxParameterCount = 1024;
- primarySetupOffset = PrimarySetupOffset;
- secondaryParameterOffset = SecondaryParameterOffset;
- }
-
- internal override void Reset()
- {
- base.Reset();
- _isPrimary = _hasMore = true;
- }
-
- internal virtual void Reset(int key, string lastName)
- {
- Reset();
- }
-
- public virtual bool MoveNext()
- {
- return _hasMore;
- }
-
- public virtual object Current()
- {
- if (_isPrimary)
- {
- _isPrimary = false;
- ParameterOffset = primarySetupOffset + (SetupCount * 2) + 2;
- if (Command != SmbComNtTransact)
- {
- if (Command == SmbComTransaction && IsResponse() == false)
- {
- ParameterOffset += StringWireLength(Name, ParameterOffset);
- }
- }
- else
- {
- if (Command == SmbComNtTransact)
- {
- ParameterOffset += 2;
- }
- }
- _pad = ParameterOffset % PaddingSize;
- _pad = _pad == 0 ? 0 : PaddingSize - _pad;
- ParameterOffset += _pad;
- TotalParameterCount = WriteParametersWireFormat(TxnBuf, _bufParameterOffset);
- _bufDataOffset = TotalParameterCount;
- // data comes right after data
- int available = MaxBufferSize - ParameterOffset;
- ParameterCount = Math.Min(TotalParameterCount, available);
- available -= ParameterCount;
- DataOffset = ParameterOffset + ParameterCount;
- _pad1 = DataOffset % PaddingSize;
- _pad1 = _pad1 == 0 ? 0 : PaddingSize - _pad1;
- DataOffset += _pad1;
- TotalDataCount = WriteDataWireFormat(TxnBuf, _bufDataOffset);
- DataCount = Math.Min(TotalDataCount, available);
- }
- else
- {
- if (Command != SmbComNtTransact)
- {
- Command = SmbComTransactionSecondary;
- }
- else
- {
- Command = SmbComNtTransactSecondary;
- }
- // totalParameterCount and totalDataCount are set ok from primary
- ParameterOffset = SecondaryParameterOffset;
- if ((TotalParameterCount - ParameterDisplacement) > 0)
- {
- _pad = ParameterOffset % PaddingSize;
- _pad = _pad == 0 ? 0 : PaddingSize - _pad;
- ParameterOffset += _pad;
- }
- // caclulate parameterDisplacement before calculating new parameterCount
- ParameterDisplacement += ParameterCount;
- int available = MaxBufferSize - ParameterOffset - _pad;
- ParameterCount = Math.Min(TotalParameterCount - ParameterDisplacement, available);
- available -= ParameterCount;
- DataOffset = ParameterOffset + ParameterCount;
- _pad1 = DataOffset % PaddingSize;
- _pad1 = _pad1 == 0 ? 0 : PaddingSize - _pad1;
- DataOffset += _pad1;
- DataDisplacement += DataCount;
- available -= _pad1;
- DataCount = Math.Min(TotalDataCount - DataDisplacement, available);
- }
- if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount && (DataDisplacement
- + DataCount) >= TotalDataCount)
- {
- _hasMore = false;
- }
- return this;
-
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(TotalParameterCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(TotalDataCount, dst, dstIndex);
- dstIndex += 2;
- if (Command != SmbComTransactionSecondary)
- {
- WriteInt2(MaxParameterCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(MaxDataCount, dst, dstIndex);
- dstIndex += 2;
- dst[dstIndex++] = MaxSetupCount;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved1
- WriteInt2(_flags, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(Timeout, dst, dstIndex);
- dstIndex += 4;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved2
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- WriteInt2(ParameterCount, dst, dstIndex);
- dstIndex += 2;
- // writeInt2(( parameterCount == 0 ? 0 : parameterOffset ), dst, dstIndex );
- WriteInt2(ParameterOffset, dst, dstIndex);
- dstIndex += 2;
- if (Command == SmbComTransactionSecondary)
- {
- WriteInt2(ParameterDisplacement, dst, dstIndex);
- dstIndex += 2;
- }
- WriteInt2(DataCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2((DataCount == 0 ? 0 : DataOffset), dst, dstIndex);
- dstIndex += 2;
- if (Command == SmbComTransactionSecondary)
- {
- WriteInt2(DataDisplacement, dst, dstIndex);
- dstIndex += 2;
- }
- else
- {
- dst[dstIndex++] = unchecked((byte)SetupCount);
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // Reserved3
- dstIndex += WriteSetupWireFormat(dst, dstIndex);
- }
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- int p = _pad;
- if (Command == SmbComTransaction && IsResponse() == false)
- {
- dstIndex += WriteString(Name, dst, dstIndex);
- }
- if (ParameterCount > 0)
- {
- while (p-- > 0)
- {
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- // Pad
- Array.Copy(TxnBuf, _bufParameterOffset, dst, dstIndex, ParameterCount);
- dstIndex += ParameterCount;
- }
- if (DataCount > 0)
- {
- p = _pad1;
- while (p-- > 0)
- {
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- // Pad1
- Array.Copy(TxnBuf, _bufDataOffset, dst, dstIndex, DataCount);
- _bufDataOffset += DataCount;
- dstIndex += DataCount;
- }
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- internal abstract int WriteSetupWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int WriteParametersWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- );
-
- internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len);
-
- internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len);
-
- public override string ToString()
- {
- return base.ToString() + ",totalParameterCount=" + TotalParameterCount
- + ",totalDataCount=" + TotalDataCount + ",maxParameterCount=" + MaxParameterCount
- + ",maxDataCount=" + MaxDataCount + ",maxSetupCount=" + (int)MaxSetupCount + ",flags=0x"
- + Hexdump.ToHexString(_flags, 2) + ",timeout=" + Timeout + ",parameterCount=" +
- ParameterCount + ",parameterOffset=" + ParameterOffset + ",parameterDisplacement="
- + ParameterDisplacement + ",dataCount=" + DataCount + ",dataOffset=" + DataOffset
- + ",dataDisplacement=" + DataDisplacement + ",setupCount=" + SetupCount + ",pad="
- + _pad + ",pad1=" + _pad1;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs
deleted file mode 100644
index 35f87594d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs
+++ /dev/null
@@ -1,206 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal abstract class SmbComTransactionResponse : ServerMessageBlock
- {
- private const int SetupOffset = 61;
-
- private const int DisconnectTid = unchecked(0x01);
-
- private const int OneWayTransaction = unchecked(0x02);
-
- private int _pad;
-
- private int _pad1;
-
- private bool _parametersDone;
-
- private bool _dataDone;
-
- protected internal int TotalParameterCount;
-
- protected internal int TotalDataCount;
-
- protected internal int ParameterCount;
-
- protected internal int ParameterOffset;
-
- protected internal int ParameterDisplacement;
-
- protected internal int DataOffset;
-
- protected internal int DataDisplacement;
-
- protected internal int SetupCount;
-
- protected internal int BufParameterStart;
-
- protected internal int BufDataStart;
-
- internal int DataCount;
-
- internal byte SubCommand;
-
- internal bool HasMore = true;
-
- internal bool IsPrimary = true;
-
- internal byte[] TxnBuf;
-
- internal int Status;
-
- internal int NumEntries;
-
- internal IFileEntry[] Results;
-
- public SmbComTransactionResponse()
- {
- // relative to headerStart
- TxnBuf = null;
- }
-
- internal override void Reset()
- {
- base.Reset();
- BufDataStart = 0;
- IsPrimary = HasMore = true;
- _parametersDone = _dataDone = false;
- }
-
- public virtual bool MoveNext()
- {
- return ErrorCode == 0 && HasMore;
- }
-
- public virtual object Current()
- {
- if (IsPrimary)
- {
- IsPrimary = false;
- }
- return this;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- TotalParameterCount = ReadInt2(buffer, bufferIndex);
- if (BufDataStart == 0)
- {
- BufDataStart = TotalParameterCount;
- }
- bufferIndex += 2;
- TotalDataCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 4;
- // Reserved
- ParameterCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- ParameterOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- ParameterDisplacement = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DataCount = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DataOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- DataDisplacement = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- SetupCount = buffer[bufferIndex] & unchecked(0xFF);
- bufferIndex += 2;
- if (SetupCount != 0)
- {
- if (Log.Level > 2)
- {
- Log.WriteLine("setupCount is not zero: " + SetupCount);
- }
- }
- return bufferIndex - start;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- _pad = _pad1 = 0;
- int n;
- if (ParameterCount > 0)
- {
- bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart);
- Array.Copy(buffer, bufferIndex, TxnBuf, BufParameterStart + ParameterDisplacement
- , ParameterCount);
- bufferIndex += ParameterCount;
- }
- if (DataCount > 0)
- {
- bufferIndex += _pad1 = DataOffset - (bufferIndex - HeaderStart);
- Array.Copy(buffer, bufferIndex, TxnBuf, BufDataStart + DataDisplacement,
- DataCount);
- bufferIndex += DataCount;
- }
- if (!_parametersDone && (ParameterDisplacement + ParameterCount) == TotalParameterCount)
- {
- _parametersDone = true;
- }
- if (!_dataDone && (DataDisplacement + DataCount) == TotalDataCount)
- {
- _dataDone = true;
- }
- if (_parametersDone && _dataDone)
- {
- HasMore = false;
- ReadParametersWireFormat(TxnBuf, BufParameterStart, TotalParameterCount);
- ReadDataWireFormat(TxnBuf, BufDataStart, TotalDataCount);
- }
- return _pad + ParameterCount + _pad1 + DataCount;
- }
-
- internal abstract int WriteSetupWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int WriteParametersWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex);
-
- internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- );
-
- internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len);
-
- internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len);
-
- public override string ToString()
- {
- return base.ToString() + ",totalParameterCount=" + TotalParameterCount
- + ",totalDataCount=" + TotalDataCount + ",parameterCount=" + ParameterCount + ",parameterOffset="
- + ParameterOffset + ",parameterDisplacement=" + ParameterDisplacement + ",dataCount="
- + DataCount + ",dataOffset=" + DataOffset + ",dataDisplacement=" + DataDisplacement
- + ",setupCount=" + SetupCount + ",pad=" + _pad + ",pad1=" + _pad1;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs
deleted file mode 100644
index 67ad04f5f..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs
+++ /dev/null
@@ -1,226 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComTreeConnectAndX : AndXServerMessageBlock
- {
- private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords"
- , true);
-
- private SmbSession _session;
-
- private bool _disconnectTid = false;
-
- private string _service;
-
- private byte[] _password;
-
- private int _passwordLength;
-
- internal string path;
-
- private static byte[] _batchLimits = { 1, 1, 1, 1, 1, 1, 1, 1, 0 };
-
- static SmbComTreeConnectAndX()
- {
- string s;
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) !=
- null)
- {
- _batchLimits[0] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory"))
- != null)
- {
- _batchLimits[2] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Delete")) != null)
- {
- _batchLimits[3] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory"))
- != null)
- {
- _batchLimits[4] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.OpenAndX")) != null)
- {
- _batchLimits[5] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Rename")) != null)
- {
- _batchLimits[6] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Transaction")) != null)
- {
- _batchLimits[7] = byte.Parse(s);
- }
- if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation"))
- != null)
- {
- _batchLimits[8] = byte.Parse(s);
- }
- }
-
- internal SmbComTreeConnectAndX(SmbSession session, string path, string service, ServerMessageBlock
- andx) : base(andx)
- {
- this._session = session;
- this.path = path;
- this._service = service;
- Command = SmbComTreeConnectAndx;
- }
-
- internal override int GetBatchLimit(byte command)
- {
- int c = command & unchecked(0xFF);
- switch (c)
- {
- case SmbComCheckDirectory:
- {
- // why isn't this just return batchLimits[c]?
- return _batchLimits[0];
- }
-
- case SmbComCreateDirectory:
- {
- return _batchLimits[2];
- }
-
- case SmbComDelete:
- {
- return _batchLimits[3];
- }
-
- case SmbComDeleteDirectory:
- {
- return _batchLimits[4];
- }
-
- case SmbComOpenAndx:
- {
- return _batchLimits[5];
- }
-
- case SmbComRename:
- {
- return _batchLimits[6];
- }
-
- case SmbComTransaction:
- {
- return _batchLimits[7];
- }
-
- case SmbComQueryInformation:
- {
- return _batchLimits[8];
- }
- }
- return 0;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal
- || _session.Auth.Password.Length > 0))
- {
- if (_session.transport.Server.EncryptedPasswords)
- {
- // encrypted
- _password = _session.Auth.GetAnsiHash(_session.transport.Server.EncryptionKey);
- _passwordLength = _password.Length;
- }
- else
- {
- if (DisablePlainTextPasswords)
- {
- throw new RuntimeException("Plain text passwords are disabled");
- }
- // plain text
- _password = new byte[(_session.Auth.Password.Length + 1) * 2];
- _passwordLength = WriteString(_session.Auth.Password, _password, 0);
- }
- }
- else
- {
- // no password in tree connect
- _passwordLength = 1;
- }
- dst[dstIndex++] = _disconnectTid ? unchecked((byte)unchecked(0x01)) : unchecked(
- (byte)unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- WriteInt2(_passwordLength, dst, dstIndex);
- return 4;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal
- || _session.Auth.Password.Length > 0))
- {
- Array.Copy(_password, 0, dst, dstIndex, _passwordLength);
- dstIndex += _passwordLength;
- }
- else
- {
- // no password in tree connect
- dst[dstIndex++] = unchecked(unchecked(0x00));
- }
- dstIndex += WriteString(path, dst, dstIndex);
- try
- {
-// Array.Copy(Runtime.GetBytesForString(_service, "ASCII"), 0, dst, dstIndex
- //, _service.Length);
- Array.Copy(Runtime.GetBytesForString(_service, "UTF-8"), 0, dst, dstIndex
- , _service.Length);
- }
- catch (UnsupportedEncodingException)
- {
- return 0;
- }
- dstIndex += _service.Length;
- dst[dstIndex++] = unchecked((byte)('\0'));
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- string result = "SmbComTreeConnectAndX[" + base.ToString() + ",disconnectTid="
- + _disconnectTid + ",passwordLength=" + _passwordLength + ",password=" + Hexdump.
- ToHexString(_password, _passwordLength, 0) + ",path=" + path + ",service=" + _service
- + "]";
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs
deleted file mode 100644
index add660b26..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComTreeConnectAndXResponse : AndXServerMessageBlock
- {
- private const int SmbSupportSearchBits = unchecked(0x0001);
-
- private const int SmbShareIsInDfs = unchecked(0x0002);
-
- internal bool SupportSearchBits;
-
- internal bool ShareIsInDfs;
-
- internal string Service;
-
- internal string NativeFileSystem = string.Empty;
-
- internal SmbComTreeConnectAndXResponse(ServerMessageBlock andx) : base(andx)
- {
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- SupportSearchBits = (buffer[bufferIndex] & SmbSupportSearchBits) == SmbSupportSearchBits;
- ShareIsInDfs = (buffer[bufferIndex] & SmbShareIsInDfs) == SmbShareIsInDfs;
- return 2;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- int start = bufferIndex;
- int len = ReadStringLength(buffer, bufferIndex, 32);
- try
- {
- //Service = Runtime.GetStringForBytes(buffer, bufferIndex, len, "ASCII");
- Service = Runtime.GetStringForBytes(buffer, bufferIndex, len, "UTF-8");
- }
- catch (UnsupportedEncodingException)
- {
- return 0;
- }
- bufferIndex += len + 1;
- // win98 observed not returning nativeFileSystem
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- string result = "SmbComTreeConnectAndXResponse[" + base.ToString() + ",supportSearchBits="
- + SupportSearchBits + ",shareIsInDfs=" + ShareIsInDfs + ",service=" + Service +
- ",nativeFileSystem=" + NativeFileSystem + "]";
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs
deleted file mode 100644
index d9eb5b2eb..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComTreeDisconnect : ServerMessageBlock
- {
- public SmbComTreeDisconnect()
- {
- Command = SmbComTreeDisconnect;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComTreeDisconnect[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs
deleted file mode 100644
index 418a69d1d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComWrite : ServerMessageBlock
- {
- private int _fid;
-
- private int _count;
-
- private int _offset;
-
- private int _remaining;
-
- private int _off;
-
- private byte[] _b;
-
- public SmbComWrite()
- {
- Command = SmbComWrite;
- }
-
- internal SmbComWrite(int fid, int offset, int remaining, byte[] b, int off, int len
- )
- {
- this._fid = fid;
- _count = len;
- this._offset = offset;
- this._remaining = remaining;
- this._b = b;
- this._off = off;
- Command = SmbComWrite;
- }
-
- internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int
- off, int len)
- {
- this._fid = fid;
- this._offset = (int)(offset & unchecked(0xFFFFFFFFL));
- this._remaining = remaining;
- this._b = b;
- this._off = off;
- _count = len;
- Digest = null;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_fid, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_count, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_offset, dst, dstIndex);
- dstIndex += 4;
- WriteInt2(_remaining, dst, dstIndex);
- dstIndex += 2;
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- dst[dstIndex++] = 0x01;
- WriteInt2(_count, dst, dstIndex);
- dstIndex += 2;
- Array.Copy(_b, _off, dst, dstIndex, _count);
- dstIndex += _count;
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComWrite[" + base.ToString() + ",fid=" + _fid + ",count=" +
- _count + ",offset=" + _offset + ",remaining=" + _remaining + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs
deleted file mode 100644
index b182fd7ff..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal class SmbComWriteAndX : AndXServerMessageBlock
- {
- private static readonly int ReadAndxBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX"
- , 1);
-
- private static readonly int CloseBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.Close"
- , 1);
-
- private int _fid;
-
- private int _remaining;
-
- private int _dataLength;
-
- private int _dataOffset;
-
- private int _off;
-
- private byte[] _b;
-
- private long _offset;
-
- private int _pad;
-
- internal int WriteMode;
-
- public SmbComWriteAndX() : base(null)
- {
- Command = SmbComWriteAndx;
- }
-
- internal SmbComWriteAndX(int fid, long offset, int remaining, byte[] b, int off,
- int len, ServerMessageBlock andx) : base(andx)
- {
- this._fid = fid;
- this._offset = offset;
- this._remaining = remaining;
- this._b = b;
- this._off = off;
- _dataLength = len;
- Command = SmbComWriteAndx;
- }
-
- internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int
- off, int len)
- {
- this._fid = fid;
- this._offset = offset;
- this._remaining = remaining;
- this._b = b;
- this._off = off;
- _dataLength = len;
- Digest = null;
- }
-
- internal override int GetBatchLimit(byte command)
- {
- if (command == SmbComReadAndx)
- {
- return ReadAndxBatchLimit;
- }
- if (command == SmbComClose)
- {
- return CloseBatchLimit;
- }
- return 0;
- }
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- _dataOffset = (dstIndex - HeaderStart) + 26;
- // 26 = off from here to pad
- _pad = (_dataOffset - HeaderStart) % 4;
- _pad = _pad == 0 ? 0 : 4 - _pad;
- _dataOffset += _pad;
- WriteInt2(_fid, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_offset, dst, dstIndex);
- dstIndex += 4;
- for (int i = 0; i < 4; i++)
- {
- dst[dstIndex++] = 0xFF;
- }
- WriteInt2(WriteMode, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_remaining, dst, dstIndex);
- dstIndex += 2;
- dst[dstIndex++] = 0x00;
- dst[dstIndex++] =0x00;
- WriteInt2(_dataLength, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_dataOffset, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_offset >> 32, dst, dstIndex);
- dstIndex += 4;
- return dstIndex - start;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- while (_pad-- > 0)
- {
- dst[dstIndex++] = 0xEE;
- }
- Array.Copy(_b, _off, dst, dstIndex, _dataLength);
- dstIndex += _dataLength;
- return dstIndex - start;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- return 0;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComWriteAndX[" + base.ToString() + ",fid=" + _fid + ",offset="
- + _offset + ",writeMode=" + WriteMode + ",remaining=" + _remaining + ",dataLength="
- + _dataLength + ",dataOffset=" + _dataOffset + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs
deleted file mode 100644
index c6749b6cb..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComWriteAndXResponse : AndXServerMessageBlock
- {
- internal long Count;
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL);
- return 8;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComWriteAndXResponse[" + base.ToString() + ",count=" + Count + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs
deleted file mode 100644
index 785d406c1..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class SmbComWriteResponse : ServerMessageBlock
- {
- internal long Count;
-
- internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
- )
- {
- Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL);
- return 8;
- }
-
- internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "SmbComWriteResponse[" + base.ToString() + ",count=" + Count + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs
deleted file mode 100644
index 0793c7541..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs
+++ /dev/null
@@ -1,302 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections.Generic;
-using System.Net;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal static class SmbConstants
- {
- public static readonly int DefaultPort = 445;
-
- public static readonly int DefaultMaxMpxCount = 10;
-
- public static readonly int DefaultResponseTimeout = 30000;
-
- public static readonly int DefaultSoTimeout = 35000;
-
- public static readonly int DefaultRcvBufSize = 60416;
-
- public static readonly int DefaultSndBufSize = 16644;
-
- public static readonly int DefaultSsnLimit = 250;
-
- public static readonly int DefaultConnTimeout = 35000;
-
- public static readonly IPAddress Laddr = Config.GetLocalHost();
-
- public static readonly int Lport = Config.GetInt("jcifs.smb.client.lport", 0);
-
- public static readonly int MaxMpxCount = Config.GetInt("jcifs.smb.client.maxMpxCount", DefaultMaxMpxCount
- );
-
- public static readonly int SndBufSize = Config.GetInt("jcifs.smb.client.snd_buf_size", DefaultSndBufSize
- );
-
- public static readonly int RcvBufSize = Config.GetInt("jcifs.smb.client.rcv_buf_size", DefaultRcvBufSize
- );
-
- public static readonly bool UseUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode",
- true);
-
- public static readonly bool ForceUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode"
- , false);
-
- public static readonly bool UseNtstatus = Config.GetBoolean("jcifs.smb.client.useNtStatus"
- , true);
-
- public static readonly bool Signpref = Config.GetBoolean("jcifs.smb.client.signingPreferred"
- , false);
-
- public static readonly bool UseNtsmbs = Config.GetBoolean("jcifs.smb.client.useNTSmbs", true
- );
-
- public static readonly bool UseExtsec = Config.GetBoolean("jcifs.smb.client.useExtendedSecurity"
- , true);
-
- public static readonly string NetbiosHostname = Config.GetProperty("jcifs.netbios.hostname"
- , null);
-
- public static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
-
- public static readonly int FlagsNone = unchecked(0x00);
-
- public static readonly int FlagsLockAndReadWriteAndUnlock = unchecked(0x01);
-
- public static readonly int FlagsReceiveBufferPosted = unchecked(0x02);
-
- public static readonly int FlagsPathNamesCaseless = unchecked(0x08);
-
- public static readonly int FlagsPathNamesCanonicalized = unchecked(0x10);
-
- public static readonly int FlagsOplockRequestedOrGranted = unchecked(0x20);
-
- public static readonly int FlagsNotifyOfModifyAction = unchecked(0x40);
-
- public static readonly int FlagsResponse = unchecked(0x80);
-
- public static readonly int Flags2None = unchecked(0x0000);
-
- public static readonly int Flags2LongFilenames = unchecked(0x0001);
-
- public static readonly int Flags2ExtendedAttributes = unchecked(0x0002);
-
- public static readonly int Flags2SecuritySignatures = unchecked(0x0004);
-
- public static readonly int Flags2ExtendedSecurityNegotiation = unchecked(0x0800);
-
- public static readonly int Flags2ResolvePathsInDfs = unchecked(0x1000);
-
- public static readonly int Flags2PermitReadIfExecutePerm = unchecked(0x2000);
-
- public static readonly int Flags2Status32 = unchecked(0x4000);
-
- public static readonly int Flags2Unicode = unchecked(0x8000);
-
- public static readonly int CapNone = unchecked(0x0000);
-
- public static readonly int CapRawMode = unchecked(0x0001);
-
- public static readonly int CapMpxMode = unchecked(0x0002);
-
- public static readonly int CapUnicode = unchecked(0x0004);
-
- public static readonly int CapLargeFiles = unchecked(0x0008);
-
- public static readonly int CapNtSmbs = unchecked(0x0010);
-
- public static readonly int CapRpcRemoteApis = unchecked(0x0020);
-
- public static readonly int CapStatus32 = unchecked(0x0040);
-
- public static readonly int CapLevelIiOplocks = unchecked(0x0080);
-
- public static readonly int CapLockAndRead = unchecked(0x0100);
-
- public static readonly int CapNtFind = unchecked(0x0200);
-
- public static readonly int CapDfs = unchecked(0x1000);
-
- public static readonly int CapExtendedSecurity = unchecked((int)(0x80000000));
-
- public static readonly int AttrReadonly = unchecked(0x01);
-
- public static readonly int AttrHidden = unchecked(0x02);
-
- public static readonly int AttrSystem = unchecked(0x04);
-
- public static readonly int AttrVolume = unchecked(0x08);
-
- public static readonly int AttrDirectory = unchecked(0x10);
-
- public static readonly int AttrArchive = unchecked(0x20);
-
- public static readonly int AttrCompressed = unchecked(0x800);
-
- public static readonly int AttrNormal = unchecked(0x080);
-
- public static readonly int AttrTemporary = unchecked(0x100);
-
- public static readonly int FileReadData = unchecked(0x00000001);
-
- public static readonly int FileWriteData = unchecked(0x00000002);
-
- public static readonly int FileAppendData = unchecked(0x00000004);
-
- public static readonly int FileReadEa = unchecked(0x00000008);
-
- public static readonly int FileWriteEa = unchecked(0x00000010);
-
- public static readonly int FileExecute = unchecked(0x00000020);
-
- public static readonly int FileDelete = unchecked(0x00000040);
-
- public static readonly int FileReadAttributes = unchecked(0x00000080);
-
- public static readonly int FileWriteAttributes = unchecked(0x00000100);
-
- public static readonly int Delete = unchecked(0x00010000);
-
- public static readonly int ReadControl = unchecked(0x00020000);
-
- public static readonly int WriteDac = unchecked(0x00040000);
-
- public static readonly int WriteOwner = unchecked(0x00080000);
-
- public static readonly int Synchronize = unchecked(0x00100000);
-
- public static readonly int GenericAll = unchecked(0x10000000);
-
- public static readonly int GenericExecute = unchecked(0x20000000);
-
- public static readonly int GenericWrite = unchecked(0x40000000);
-
- public static readonly int GenericRead = unchecked((int)(0x80000000));
-
- public static readonly int FlagsTargetMustBeFile = unchecked(0x0001);
-
- public static readonly int FlagsTargetMustBeDirectory = unchecked(0x0002);
-
- public static readonly int FlagsCopyTargetModeAscii = unchecked(0x0004);
-
- public static readonly int FlagsCopySourceModeAscii = unchecked(0x0008);
-
- public static readonly int FlagsVerifyAllWrites = unchecked(0x0010);
-
- public static readonly int FlagsTreeCopy = unchecked(0x0020);
-
- public static readonly int OpenFunctionFailIfExists = unchecked(0x0000);
-
- public static readonly int OpenFunctionOverwriteIfExists = unchecked(0x0020);
-
- public static readonly int Pid = (int)(new Random().NextDouble() * 65536d);
-
- public static readonly int SecurityShare = unchecked(0x00);
-
- public static readonly int SecurityUser = unchecked(0x01);
-
- public static readonly int CmdOffset = 4;
-
- public static readonly int ErrorCodeOffset = 5;
-
- public static readonly int FlagsOffset = 9;
-
- public static readonly int SignatureOffset = 14;
-
- public static readonly int TidOffset = 24;
-
- public static readonly int HeaderLength = 32;
-
- public static readonly long MillisecondsBetween1970And1601 = 11644473600000L;
-
- public static readonly TimeZoneInfo Tz = TimeZoneInfo.Local;
-
- public static readonly bool UseBatching = Config.GetBoolean("jcifs.smb.client.useBatching"
- , true);
-
- public static readonly string OemEncoding = Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding
- );
-
- public static readonly string UniEncoding = "UTF-16LE";
-
- public static readonly int DefaultFlags2 = Flags2LongFilenames | Flags2ExtendedAttributes
- | (UseExtsec ? Flags2ExtendedSecurityNegotiation : 0) | (Signpref ? Flags2SecuritySignatures
- : 0) | (UseNtstatus ? Flags2Status32 : 0) | (UseUnicode ? Flags2Unicode : 0
- );
-
- public static readonly int DefaultCapabilities = (UseNtsmbs ? CapNtSmbs : 0) | (UseNtstatus
- ? CapStatus32 : 0) | (UseUnicode ? CapUnicode : 0) | CapDfs;
-
- public static readonly int Flags2 = Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2
- );
-
- public static readonly int Capabilities = Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities
- );
-
- public static readonly bool TcpNodelay = Config.GetBoolean("jcifs.smb.client.tcpNoDelay",
- false);
-
- public static readonly int ResponseTimeout = Config.GetInt("jcifs.smb.client.responseTimeout"
- , DefaultResponseTimeout);
-
- public static readonly List<SmbTransport> Connections = new List<SmbTransport>();
-
- public static readonly int SsnLimit = Config.GetInt("jcifs.smb.client.ssnLimit", DefaultSsnLimit
- );
-
- public static readonly int SoTimeout = Config.GetInt("jcifs.smb.client.soTimeout", DefaultSoTimeout
- );
-
- public static readonly int ConnTimeout = Config.GetInt("jcifs.smb.client.connTimeout", DefaultConnTimeout
- );
-
- public static readonly string NativeOs = Config.GetProperty("jcifs.smb.client.nativeOs", Runtime
- .GetProperty("os.name"));
-
- public static readonly string NativeLanman = Config.GetProperty("jcifs.smb.client.nativeLanMan"
- , "jCIFS");
-
- public static readonly int VcNumber = 1;
-
- public static SmbTransport NullTransport = new SmbTransport(null, 0, null, 0);
- // file attribute encoding
- // extended file attribute encoding(others same as above)
- // access mask encoding
- // 1
- // 2
- // 3
- // 4
- // 5
- // 6
- // 7
- // 8
- // 9
- // 16
- // 17
- // 18
- // 19
- // 20
- // 28
- // 29
- // 30
- // 31
- // flags for move and copy
- // open function
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs
deleted file mode 100644
index ea8a0b846..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs
+++ /dev/null
@@ -1,212 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>
- /// There are hundreds of error codes that may be returned by a CIFS
- /// server.
- /// </summary>
- /// <remarks>
- /// There are hundreds of error codes that may be returned by a CIFS
- /// server. Rather than represent each with it's own <code>Exception</code>
- /// class, this class represents all of them. For many of the popular
- /// error codes, constants and text messages like "The device is not ready"
- /// are provided.
- /// <p>
- /// The jCIFS client maps DOS error codes to NTSTATUS codes. This means that
- /// the user may recieve a different error from a legacy server than that of
- /// a newer varient such as Windows NT and above. If you should encounter
- /// such a case, please report it to jcifs at samba dot org and we will
- /// change the mapping.
- /// </remarks>
-
- public class SmbException : IOException
- {
-
- internal static string GetMessageByCode(int errcode)
- {
- if (errcode == 0)
- {
- return "NT_STATUS_SUCCESS";
- }
- if ((errcode & unchecked((int)(0xC0000000))) == unchecked((int)(0xC0000000)))
- {
- int min = 1;
- int max = NtStatus.NtStatusCodes.Length - 1;
- while (max >= min)
- {
- int mid = (min + max) / 2;
- if (errcode > NtStatus.NtStatusCodes[mid])
- {
- min = mid + 1;
- }
- else
- {
- if (errcode < NtStatus.NtStatusCodes[mid])
- {
- max = mid - 1;
- }
- else
- {
- return NtStatus.NtStatusMessages[mid];
- }
- }
- }
- }
- else
- {
- int min = 0;
- int max = DosError.DosErrorCodes.Length - 1;
- while (max >= min)
- {
- int mid = (min + max) / 2;
- if (errcode > DosError.DosErrorCodes[mid][0])
- {
- min = mid + 1;
- }
- else
- {
- if (errcode < DosError.DosErrorCodes[mid][0])
- {
- max = mid - 1;
- }
- else
- {
- return DosError.DosErrorMessages[mid];
- }
- }
- }
- }
- return "0x" + Hexdump.ToHexString(errcode, 8);
- }
-
- internal static int GetStatusByCode(int errcode)
- {
- if ((errcode & unchecked((int)(0xC0000000))) != 0)
- {
- return errcode;
- }
- int min = 0;
- int max = DosError.DosErrorCodes.Length - 1;
- while (max >= min)
- {
- int mid = (min + max) / 2;
- if (errcode > DosError.DosErrorCodes[mid][0])
- {
- min = mid + 1;
- }
- else
- {
- if (errcode < DosError.DosErrorCodes[mid][0])
- {
- max = mid - 1;
- }
- else
- {
- return DosError.DosErrorCodes[mid][1];
- }
- }
- }
- return NtStatus.NtStatusUnsuccessful;
- }
-
- internal static string GetMessageByWinerrCode(int errcode)
- {
- int min = 0;
- int max = WinError.WinerrCodes.Length - 1;
- while (max >= min)
- {
- int mid = (min + max) / 2;
- if (errcode > WinError.WinerrCodes[mid])
- {
- min = mid + 1;
- }
- else
- {
- if (errcode < WinError.WinerrCodes[mid])
- {
- max = mid - 1;
- }
- else
- {
- return WinError.WinerrMessages[mid];
- }
- }
- }
- return errcode + string.Empty;
- }
-
- private int _status;
-
- private Exception _rootCause;
-
- public SmbException()
- {
- }
-
- internal SmbException(int errcode, Exception rootCause) : base(GetMessageByCode(errcode
- ))
- {
- _status = GetStatusByCode(errcode);
- this._rootCause = rootCause;
- }
-
- public SmbException(string msg) : base(msg)
- {
- _status = NtStatus.NtStatusUnsuccessful;
- }
-
- public SmbException(string msg, Exception rootCause) : base(msg)
- {
- this._rootCause = rootCause;
- _status = NtStatus.NtStatusUnsuccessful;
- }
-
- public SmbException(int errcode, bool winerr) : base(winerr ? GetMessageByWinerrCode
- (errcode) : GetMessageByCode(errcode))
- {
- _status = winerr ? errcode : GetStatusByCode(errcode);
- }
-
- public virtual int GetNtStatus()
- {
- return _status;
- }
-
- public virtual Exception GetRootCause()
- {
- return _rootCause;
- }
-
- public override string ToString()
- {
- if (_rootCause != null)
- {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- Runtime.PrintStackTrace(_rootCause, pw);
- return base.ToString() + "\n" + sw;
- }
- return base.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs
deleted file mode 100644
index 151ec35c4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs
+++ /dev/null
@@ -1,3755 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Text;
-using SharpCifs.Dcerpc;
-using SharpCifs.Dcerpc.Msrpc;
-using SharpCifs.Netbios;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>This class represents a resource on an SMB network.</summary>
- /// <remarks>
- /// This class represents a resource on an SMB network. Mainly these
- /// resources are files and directories however an <code>SmbFile</code>
- /// may also refer to servers and workgroups. If the resource is a file or
- /// directory the methods of <code>SmbFile</code> follow the behavior of
- /// the well known
- /// <see cref="FilePath">Sharpen.FilePath</see>
- /// class. One fundamental difference
- /// is the usage of a URL scheme [1] to specify the target file or
- /// directory. SmbFile URLs have the following syntax:
- /// <blockquote><pre>
- /// smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]]
- /// </pre></blockquote>
- /// This example:
- /// <blockquote><pre>
- /// smb://storage15/public/foo.txt
- /// </pre></blockquote>
- /// would reference the file <code>foo.txt</code> in the share
- /// <code>public</code> on the server <code>storage15</code>. In addition
- /// to referencing files and directories, jCIFS can also address servers,
- /// and workgroups.
- /// <p>
- /// <font color="#800000"><i>Important: all SMB URLs that represent
- /// workgroups, servers, shares, or directories require a trailing slash '/'.
- /// </i></font>
- /// <p>
- /// When using the <tt>java.net.URL</tt> class with
- /// 'smb://' URLs it is necessary to first call the static
- /// <tt>jcifs.Config.registerSmbURLHandler();</tt> method. This is required
- /// to register the SMB protocol handler.
- /// <p>
- /// The userinfo component of the SMB URL (<tt>domain;user:pass</tt>) must
- /// be URL encoded if it contains reserved characters. According to RFC 2396
- /// these characters are non US-ASCII characters and most meta characters
- /// however jCIFS will work correctly with anything but '@' which is used
- /// to delimit the userinfo component from the server and '%' which is the
- /// URL escape character itself.
- /// <p>
- /// The server
- /// component may a traditional NetBIOS name, a DNS name, or IP
- /// address. These name resolution mechanisms and their resolution order
- /// can be changed (See <a href="../../../resolver.html">Setting Name
- /// Resolution Properties</a>). The servername and path components are
- /// not case sensitive but the domain, username, and password components
- /// are. It is also likely that properties must be specified for jcifs
- /// to function (See <a href="../../overview-summary.html#scp">Setting
- /// JCIFS Properties</a>). Here are some examples of SMB URLs with brief
- /// descriptions of what they do:
- /// <p>[1] This URL scheme is based largely on the <i>SMB
- /// Filesharing URL Scheme</i> IETF draft.
- /// <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
- /// <tr bgcolor="#ccccff">
- /// <td colspan="2"><b>SMB URL Examples</b></td>
- /// <tr><td width="20%"><b>URL</b></td><td><b>Description</b></td></tr>
- /// <tr><td width="20%"><code>smb://users-nyc;miallen:mypass@angus/tmp/</code></td><td>
- /// This URL references a share called <code>tmp</code> on the server
- /// <code>angus</code> as user <code>miallen</code> who's password is
- /// <code>mypass</code>.
- /// </td></tr>
- /// <tr><td width="20%">
- /// <code>smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt</code></td><td>
- /// A relativly sophisticated example that references a file
- /// <code>msmith1</code>'s desktop as user <code>Administrator</code>. Notice the '@' is URL encoded with the '%40' hexcode escape.
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://angus/</code></td><td>
- /// This references only a server. The behavior of some methods is different
- /// in this context(e.g. you cannot <code>delete</code> a server) however
- /// as you might expect the <code>list</code> method will list the available
- /// shares on this server.
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://myworkgroup/</code></td><td>
- /// This syntactically is identical to the above example. However if
- /// <code>myworkgroup</code> happends to be a workgroup(which is indeed
- /// suggested by the name) the <code>list</code> method will return
- /// a list of servers that have registered themselves as members of
- /// <code>myworkgroup</code>.
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://</code></td><td>
- /// Just as <code>smb://server/</code> lists shares and
- /// <code>smb://workgroup/</code> lists servers, the <code>smb://</code>
- /// URL lists all available workgroups on a netbios LAN. Again,
- /// in this context many methods are not valid and return default
- /// values(e.g. <code>isHidden</code> will always return false).
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://angus.foo.net/d/jcifs/pipes.doc</code></td><td>
- /// The server name may also be a DNS name as it is in this example. See
- /// <a href="../../../resolver.html">Setting Name Resolution Properties</a>
- /// for details.
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://192.168.1.15/ADMIN$/</code></td><td>
- /// The server name may also be an IP address. See &lt;a
- /// href="../../../resolver.html"&gt;Setting Name Resolution Properties</a>
- /// for details.
- /// </td></tr>
- /// <tr><td width="20%">
- /// <code>smb://domain;username:password@server/share/path/to/file.txt</code></td><td>
- /// A prototypical example that uses all the fields.
- /// </td></tr>
- /// <tr><td width="20%"><code>smb://myworkgroup/angus/ &lt;-- ILLEGAL </code></td><td>
- /// Despite the hierarchial relationship between workgroups, servers, and
- /// filesystems this example is not valid.
- /// </td></tr>
- /// <tr><td width="20%">
- /// <code>smb://server/share/path/to/dir &lt;-- ILLEGAL </code></td><td>
- /// URLs that represent workgroups, servers, shares, or directories require a trailing slash '/'.
- /// </td></tr>
- /// <tr><td width="20%">
- /// <code>smb://MYGROUP/?SERVER=192.168.10.15</code></td><td>
- /// SMB URLs support some query string parameters. In this example
- /// the <code>SERVER</code> parameter is used to override the
- /// server name service lookup to contact the server 192.168.10.15
- /// (presumably known to be a master
- /// browser) for the server list in workgroup <code>MYGROUP</code>.
- /// </td></tr>
- /// </table>
- /// <p>A second constructor argument may be specified to augment the URL
- /// for better programmatic control when processing many files under
- /// a common base. This is slightly different from the corresponding
- /// <code>java.io.File</code> usage; a '/' at the beginning of the second
- /// parameter will still use the server component of the first parameter. The
- /// examples below illustrate the resulting URLs when this second contructor
- /// argument is used.
- /// <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
- /// <tr bgcolor="#ccccff">
- /// <td colspan="3">
- /// <b>Examples Of SMB URLs When Augmented With A Second Constructor Parameter</b></td>
- /// <tr><td width="20%">
- /// <b>First Parameter</b></td><td><b>Second Parameter</b></td><td><b>Result</b></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/a/b/
- /// </code></td><td width="20%"><code>
- /// c/d/
- /// </code></td><td><code>
- /// smb://host/share/a/b/c/d/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/foo/bar/
- /// </code></td><td width="20%"><code>
- /// /share2/zig/zag
- /// </code></td><td><code>
- /// smb://host/share2/zig/zag
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/foo/bar/
- /// </code></td><td width="20%"><code>
- /// ../zip/
- /// </code></td><td><code>
- /// smb://host/share/foo/zip/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/zig/zag
- /// </code></td><td width="20%"><code>
- /// smb://foo/bar/
- /// </code></td><td><code>
- /// smb://foo/bar/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/foo/
- /// </code></td><td width="20%"><code>
- /// ../.././.././../foo/
- /// </code></td><td><code>
- /// smb://host/foo/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://host/share/zig/zag
- /// </code></td><td width="20%"><code>
- /// /
- /// </code></td><td><code>
- /// smb://host/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://server/
- /// </code></td><td width="20%"><code>
- /// ../
- /// </code></td><td><code>
- /// smb://server/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://
- /// </code></td><td width="20%"><code>
- /// myworkgroup/
- /// </code></td><td><code>
- /// smb://myworkgroup/
- /// </code></td></tr>
- /// <tr><td width="20%"><code>
- /// smb://myworkgroup/
- /// </code></td><td width="20%"><code>
- /// angus/
- /// </code></td><td><code>
- /// smb://myworkgroup/angus/ &lt;-- ILLEGAL<br />(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.)
- /// </code></td></tr>
- /// </table>
- /// <p>Instances of the <code>SmbFile</code> class are immutable; that is,
- /// once created, the abstract pathname represented by an SmbFile object
- /// will never change.
- /// </remarks>
- /// <seealso cref="FilePath">Sharpen.FilePath</seealso>
- public class SmbFile : UrlConnection
- {
- internal const int ORdonly = 0x01;
-
- internal const int OWronly = 0x02;
-
- internal const int ORdwr = 0x03;
-
- internal const int OAppend = 0x04;
-
- internal const int OCreat = 0x0010;
-
- internal const int OExcl = 0x0020;
-
- internal const int OTrunc = 0x0040;
-
- /// <summary>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients (including other threads making calls into jCIFS)
- /// will not be permitted to access the target file and will receive "The
- /// file is being accessed by another process" message.
- /// </summary>
- /// <remarks>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients (including other threads making calls into jCIFS)
- /// will not be permitted to access the target file and will receive "The
- /// file is being accessed by another process" message.
- /// </remarks>
- public const int FileNoShare = 0x00;
-
- /// <summary>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to read from the target file while
- /// this file is open.
- /// </summary>
- /// <remarks>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to read from the target file while
- /// this file is open. This constant may be logically OR'd with other share
- /// access flags.
- /// </remarks>
- public const int FileShareRead = 0x01;
-
- /// <summary>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to write to the target file while
- /// this file is open.
- /// </summary>
- /// <remarks>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to write to the target file while
- /// this file is open. This constant may be logically OR'd with other share
- /// access flags.
- /// </remarks>
- public const int FileShareWrite = 0x02;
-
- /// <summary>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to delete the target file while
- /// this file is open.
- /// </summary>
- /// <remarks>
- /// When specified as the <tt>shareAccess</tt> constructor parameter,
- /// other SMB clients will be permitted to delete the target file while
- /// this file is open. This constant may be logically OR'd with other share
- /// access flags.
- /// </remarks>
- public const int FileShareDelete = 0x04;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
- /// with <tt>setAttributes()</tt> will be read-only
- /// </summary>
- public const int AttrReadonly = 0x01;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
- /// with <tt>setAttributes()</tt> will be hidden
- /// </summary>
- public const int AttrHidden = 0x02;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
- /// with <tt>setAttributes()</tt> will be a system file
- /// </summary>
- public const int AttrSystem = 0x04;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> is
- /// a volume
- /// </summary>
- public const int AttrVolume = 0x08;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> is
- /// a directory
- /// </summary>
- public const int AttrDirectory = 0x10;
-
- /// <summary>
- /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
- /// with <tt>setAttributes()</tt> is an archived file
- /// </summary>
- public const int AttrArchive = 0x20;
-
- internal const int AttrCompressed = 0x800;
-
- internal const int AttrNormal = 0x080;
-
- internal const int AttrTemporary = 0x100;
-
- internal const int AttrGetMask = 0x7FFF;
-
- internal const int AttrSetMask = 0x30A7;
-
- internal const int DefaultAttrExpirationPeriod = 5000;
-
- internal static readonly int HashDot = ".".GetHashCode();
-
- internal static readonly int HashDotDot = "..".GetHashCode();
-
- //internal static LogStream log = LogStream.GetInstance();
- public LogStream Log
- {
- get { return LogStream.GetInstance(); }
- }
-
- internal static long AttrExpirationPeriod;
-
- internal static bool IgnoreCopyToException;
-
- static SmbFile()
- {
- // Open Function Encoding
- // create if the file does not exist
- // fail if the file exists
- // truncate if the file exists
- // share access
- // file attribute encoding
- // extended file attribute encoding(others same as above)
- /*try
- {
- Sharpen.Runtime.GetType("jcifs.Config");
- }
- catch (TypeLoadException cnfe)
- {
- Sharpen.Runtime.PrintStackTrace(cnfe);
- }*/
-
- AttrExpirationPeriod = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod
- );
- IgnoreCopyToException = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException"
- , true);
- Dfs = new Dfs();
- }
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a regular file or directory.
- /// </summary>
- public const int TypeFilesystem = 0x01;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a workgroup.
- /// </summary>
- public const int TypeWorkgroup = 0x02;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a server.
- /// </summary>
- public const int TypeServer = 0x04;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a share.
- /// </summary>
- public const int TypeShare = 0x08;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a named pipe.
- /// </summary>
- public const int TypeNamedPipe = 0x10;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a printer.
- /// </summary>
- public const int TypePrinter = 0x20;
-
- /// <summary>
- /// Returned by
- /// <see cref="GetType()">GetType()</see>
- /// if the resource this <tt>SmbFile</tt>
- /// represents is a communications device.
- /// </summary>
- public const int TypeComm = 0x40;
-
- private string _canon;
-
- private string _share;
-
- private long _createTime;
-
- private long _lastModified;
-
- private int _attributes;
-
- private long _attrExpiration;
-
- private long _size;
-
- private long _sizeExpiration;
-
- private bool _isExists;
-
- private int _shareAccess = FileShareRead | FileShareWrite | FileShareDelete;
-
- private bool _enableDfs = Config.GetBoolean("jcifs.smb.client.enabledfs", false);
-
- private SmbComBlankResponse _blankResp;
-
- private DfsReferral _dfsReferral;
-
- protected internal static Dfs Dfs;
-
- internal NtlmPasswordAuthentication Auth;
-
- internal SmbTree Tree;
-
- internal string Unc;
-
- internal int Fid;
-
- internal int Type;
-
- internal bool Opened;
-
- internal int TreeNum;
-
- public bool EnableDfs
- {
- get { return _enableDfs; }
- set { _enableDfs = value; }
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such as
- /// a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such as
- /// a file or directory. See the description and examples of smb URLs above.
- /// </remarks>
- /// <param name="url">A URL string</param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>parent</code> and <code>child</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- public SmbFile(string url)
- : this(new Uri(url))
- {
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory. The second parameter is a relative path from
- /// the <code>parent SmbFile</code>. See the description above for examples
- /// of using the second <code>name</code> parameter.
- /// </remarks>
- /// <param name="context">A base <code>SmbFile</code></param>
- /// <param name="name">A path string relative to the <code>parent</code> paremeter</param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>parent</code> and <code>child</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- /// <exception cref="UnknownHostException">If the server or workgroup of the <tt>context</tt> file cannot be determined
- /// </exception>
- public SmbFile(SmbFile context, string name)
- : this(context.IsWorkgroup0
- () ? new Uri("smb://" + name) : new Uri(context.Url.AbsoluteUri + name),
- context.Auth)
- {
-
- this._enableDfs = context.EnableDfs;
-
- if (!context.IsWorkgroup0())
- {
- Addresses = context.Addresses;
-
- if (context._share != null)
- {
- Tree = context.Tree;
- _dfsReferral = context._dfsReferral;
- }
- }
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory. The second parameter is a relative path from
- /// the <code>parent</code>. See the description above for examples of
- /// using the second <code>chile</code> parameter.
- /// </remarks>
- /// <param name="context">A URL string</param>
- /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>context</code> and <code>name</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- /*public SmbFile(string context, string name)
- : this(new Uri(new Uri(null, context), name))
- {
- }*/
-
- public SmbFile(string context, string name)
- : this(new Uri(context + name))
- {
-
- }
-
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </remarks>
- /// <param name="url">A URL string</param>
- /// <param name="auth">The credentials the client should use for authentication</param>
- /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
- /// </exception>
- public SmbFile(string url, NtlmPasswordAuthentication auth)
- : this(new Uri(url, UriKind.RelativeOrAbsolute),
- auth)
- {
-
- }
-
- /// <summary>Constructs an SmbFile representing a file on an SMB network.</summary>
- /// <remarks>
- /// Constructs an SmbFile representing a file on an SMB network. The
- /// <tt>shareAccess</tt> parameter controls what permissions other
- /// clients have when trying to access the same file while this instance
- /// is still open. This value is either <tt>FILE_NO_SHARE</tt> or any
- /// combination of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>,
- /// and <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
- /// </remarks>
- /// <param name="url">A URL string</param>
- /// <param name="auth">The credentials the client should use for authentication</param>
- /// <param name="shareAccess">Specifies what access other clients have while this file is open.
- /// </param>
- /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
- /// </exception>
- public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess)
- : this
- (new Uri(url), auth)
- {
- // Initially null; set by getUncPath; dir must end with '/'
- // Can be null
- // For getDfsPath() and getServerWithDfs()
- // Cannot be null
- // Initially null
- // Initially null; set by getUncPath; never ends with '/'
- // Initially 0; set by open()
- if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
- 0)
- {
- throw new RuntimeException("Illegal shareAccess parameter");
- }
- this._shareAccess = shareAccess;
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory. The second parameter is a relative path from
- /// the <code>context</code>. See the description above for examples of
- /// using the second <code>name</code> parameter.
- /// </remarks>
- /// <param name="context">A URL string</param>
- /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
- /// <param name="auth">The credentials the client should use for authentication</param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>context</code> and <code>name</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- public SmbFile(string context, string name, NtlmPasswordAuthentication auth)
- : this
- (new Uri(context + name)
- , auth)
- {
-
- }
-
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory. The second parameter is a relative path from
- /// the <code>context</code>. See the description above for examples of
- /// using the second <code>name</code> parameter. The <tt>shareAccess</tt>
- /// parameter controls what permissions other clients have when trying
- /// to access the same file while this instance is still open. This
- /// value is either <tt>FILE_NO_SHARE</tt> or any combination
- /// of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and
- /// <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
- /// </remarks>
- /// <param name="context">A URL string</param>
- /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
- /// <param name="auth">The credentials the client should use for authentication</param>
- /// <param name="shareAccess">Specifies what access other clients have while this file is open.
- /// </param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>context</code> and <code>name</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- public SmbFile(string context, string name, NtlmPasswordAuthentication auth, int
- shareAccess)
- : this(new Uri(context + name), auth)
- {
- if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
- 0)
- {
- throw new RuntimeException("Illegal shareAccess parameter");
- }
- this._shareAccess = shareAccess;
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory. The second parameter is a relative path from
- /// the <code>context</code>. See the description above for examples of
- /// using the second <code>name</code> parameter. The <tt>shareAccess</tt>
- /// parameter controls what permissions other clients have when trying
- /// to access the same file while this instance is still open. This
- /// value is either <tt>FILE_NO_SHARE</tt> or any combination
- /// of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and
- /// <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
- /// </remarks>
- /// <param name="context">A base <code>SmbFile</code></param>
- /// <param name="name">A path string relative to the <code>context</code> file path</param>
- /// <param name="shareAccess">Specifies what access other clients have while this file is open.
- /// </param>
- /// <exception cref="System.UriFormatException">
- /// If the <code>context</code> and <code>name</code> parameters
- /// do not follow the prescribed syntax
- /// </exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFile(SmbFile context, string name, int shareAccess)
- : this(context.IsWorkgroup0() ? new Uri("smb://" + name) : new Uri(
- context.Url.AbsoluteUri + name), context.Auth)
- {
- if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
- 0)
- {
- throw new RuntimeException("Illegal shareAccess parameter");
- }
-
- if (!context.IsWorkgroup0())
- {
- this.Addresses = context.Addresses;
-
- if (context._share != null || context.Tree != null)
- {
- Tree = context.Tree;
- _dfsReferral = context._dfsReferral;
- }
- }
-
- this._shareAccess = shareAccess;
- this._enableDfs = context.EnableDfs;
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory from a <tt>URL</tt> object.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory from a <tt>URL</tt> object.
- /// </remarks>
- /// <param name="url">The URL of the target resource</param>
- protected SmbFile(Uri url)
- : this(url, new NtlmPasswordAuthentication(url.GetUserInfo
- ()))
- {
- }
-
- /// <summary>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory from a <tt>URL</tt> object and an
- /// <tt>NtlmPasswordAuthentication</tt> object.
- /// </summary>
- /// <remarks>
- /// Constructs an SmbFile representing a resource on an SMB network such
- /// as a file or directory from a <tt>URL</tt> object and an
- /// <tt>NtlmPasswordAuthentication</tt> object.
- /// </remarks>
- /// <param name="url">The URL of the target resource</param>
- /// <param name="auth">The credentials the client should use for authentication</param>
- public SmbFile(Uri url, NtlmPasswordAuthentication auth)
- {
- this.Auth = auth ?? new NtlmPasswordAuthentication(url.GetUserInfo());
- Url = url;
- GetUncPath0();
- }
-
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- /*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes
- , long createTime, long lastModified, long size)
- : this(context.IsWorkgroup0() ?
- new Uri(null, "smb://" + name + "/") : new Uri(context.url,
- name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/
- internal SmbFile(SmbFile context, string name, int type, int attributes
- , long createTime, long lastModified, long size)
- : this(context.IsWorkgroup0() ?
- new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri +
- name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty)))
- {
- Auth = context.Auth;
- if (context._share != null)
- {
- Tree = context.Tree;
- _dfsReferral = context._dfsReferral;
- }
- int last = name.Length - 1;
- if (name[last] == '/')
- {
- name = Runtime.Substring(name, 0, last);
- }
- if (context._share == null)
- {
- Unc = "\\";
- }
- else
- {
- if (context.Unc.Equals("\\"))
- {
- Unc = '\\' + name;
- }
- else
- {
- Unc = context.Unc + '\\' + name;
- }
- }
-
- if (!context.IsWorkgroup0())
- {
- Addresses = context.Addresses;
- }
-
- this._enableDfs = context.EnableDfs;
-
- this.Type = type;
- this._attributes = attributes;
- this._createTime = createTime;
- this._lastModified = lastModified;
- this._size = size;
- _isExists = true;
- _attrExpiration = _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- }
-
- private SmbComBlankResponse Blank_resp()
- {
- if (_blankResp == null)
- {
- _blankResp = new SmbComBlankResponse();
- }
- return _blankResp;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void ResolveDfs(ServerMessageBlock request)
- {
- if (!_enableDfs)
- {
- Connect0();
- return;
- }
-
- if (request is SmbComClose)
- {
- return;
- }
- Connect0();
- DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc
- , Auth);
- if (dr != null)
- {
- string service = null;
- if (request != null)
- {
- switch (request.Command)
- {
- case ServerMessageBlock.SmbComTransaction:
- case ServerMessageBlock.SmbComTransaction2:
- {
- switch (((SmbComTransaction)request).SubCommand & 0xFF)
- {
- case SmbComTransaction.Trans2GetDfsReferral:
- {
- break;
- }
-
- default:
- {
- service = "A:";
- break;
- }
- }
- break;
- }
-
- default:
- {
- service = "A:";
- break;
- }
- }
- }
- DfsReferral start = dr;
- SmbException se = null;
- do
- {
- try
- {
- if (Log.Level >= 2)
- {
- Log.WriteLine("DFS redirect: " + dr);
- }
- UniAddress addr = UniAddress.GetByName(dr.Server);
- SmbTransport trans = SmbTransport.GetSmbTransport(addr, Url.Port);
- trans.Connect();
- Tree = trans.GetSmbSession(Auth).GetSmbTree(dr.Share, service);
- if (dr != start && dr.Key != null)
- {
- dr.Map.Put(dr.Key, dr);
- }
- se = null;
- break;
- }
- catch (IOException ioe)
- {
- if (ioe is SmbException)
- {
- se = (SmbException)ioe;
- }
- else
- {
- se = new SmbException(dr.Server, ioe);
- }
- }
- dr = dr.Next;
- }
- while (dr != start);
- if (se != null)
- {
- throw se;
- }
- if (Log.Level >= 3)
- {
- Log.WriteLine(dr);
- }
- _dfsReferral = dr;
- if (dr.PathConsumed < 0)
- {
- dr.PathConsumed = 0;
- }
- else
- {
- if (dr.PathConsumed > Unc.Length)
- {
- dr.PathConsumed = Unc.Length;
- }
- }
- string dunc = Runtime.Substring(Unc, dr.PathConsumed);
- if (dunc.Equals(string.Empty))
- {
- dunc = "\\";
- }
- if (!dr.Path.Equals(string.Empty))
- {
- dunc = "\\" + dr.Path + dunc;
- }
- Unc = dunc;
- if (request != null && request.Path != null && request.Path.EndsWith("\\") && dunc
- .EndsWith("\\") == false)
- {
- dunc += "\\";
- }
- if (request != null)
- {
- request.Path = dunc;
- request.Flags2 |= SmbConstants.Flags2ResolvePathsInDfs;
- }
- }
- else
- {
- if (Tree.InDomainDfs && !(request is NtTransQuerySecurityDesc) && !(request is SmbComClose
- ) && !(request is SmbComFindClose2))
- {
- throw new SmbException(NtStatus.NtStatusNotFound, false);
- }
- if (request != null)
- {
- request.Flags2 &= ~SmbConstants.Flags2ResolvePathsInDfs;
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
- )
- {
- for (; ; )
- {
- ResolveDfs(request);
- try
- {
- Tree.Send(request, response);
- break;
- }
- catch (DfsReferral dre)
- {
- if (dre.ResolveHashes)
- {
- throw;
- }
- request.Reset();
- }
- }
- }
-
- internal static string QueryLookup(string query, string param)
- {
- char[] instr = query.ToCharArray();
- int i;
- int ch;
- int st;
- int eq;
- st = eq = 0;
- for (i = 0; i < instr.Length; i++)
- {
- ch = instr[i];
- if (ch == '&')
- {
- if (eq > st)
- {
- string p = new string(instr, st, eq - st);
- if (Runtime.EqualsIgnoreCase(p, param))
- {
- eq++;
- return new string(instr, eq, i - eq);
- }
- }
- st = i + 1;
- }
- else
- {
- if (ch == '=')
- {
- eq = i;
- }
- }
- }
- if (eq > st)
- {
- string p = new string(instr, st, eq - st);
- if (Runtime.EqualsIgnoreCase(p, param))
- {
- eq++;
- return new string(instr, eq, instr.Length - eq);
- }
- }
- return null;
- }
-
- internal UniAddress[] Addresses;
-
- internal int AddressIndex;
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual UniAddress GetAddress()
- {
- if (AddressIndex == 0)
- {
- return GetFirstAddress();
- }
- return Addresses[AddressIndex - 1];
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual UniAddress GetFirstAddress()
- {
- AddressIndex = 0;
- string host = Url.GetHost();
- string path = Url.AbsolutePath;
- string query = Url.GetQuery();
-
- if (Addresses != null && Addresses.Length > 0)
- {
- return GetNextAddress();
- }
-
- if (query != null)
- {
- string server = QueryLookup(query, "server");
- if (!string.IsNullOrEmpty(server))
- {
- Addresses = new UniAddress[1];
- Addresses[0] = UniAddress.GetByName(server);
- return GetNextAddress();
- }
- string address = QueryLookup(query, "address");
- if (!string.IsNullOrEmpty(address))
- {
- byte[] ip = Extensions.GetAddressByName(address).GetAddressBytes();
- Addresses = new UniAddress[1];
- //addresses[0] = new UniAddress(IPAddress.Parse(host, ip));
- Addresses[0] = new UniAddress(IPAddress.Parse(host));
- return GetNextAddress();
- }
- }
- if (host.Length == 0)
- {
- try
- {
- NbtAddress addr = NbtAddress.GetByName(NbtAddress.MasterBrowserName, 0x01, null);
- Addresses = new UniAddress[1];
- Addresses[0] = UniAddress.GetByName(addr.GetHostAddress());
- }
- catch (UnknownHostException uhe)
- {
- NtlmPasswordAuthentication.InitDefaults();
- if (NtlmPasswordAuthentication.DefaultDomain.Equals("?"))
- {
- throw;
- }
- Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, true
- );
- }
- }
- else
- {
- if (path.Length == 0 || path.Equals("/"))
- {
- Addresses = UniAddress.GetAllByName(host, true);
- }
- else
- {
- Addresses = UniAddress.GetAllByName(host, false);
- }
- }
- return GetNextAddress();
- }
-
- internal virtual UniAddress GetNextAddress()
- {
- UniAddress addr = null;
- if (AddressIndex < Addresses.Length)
- {
- addr = Addresses[AddressIndex++];
- }
- return addr;
- }
-
- internal virtual bool HasNextAddress()
- {
- return AddressIndex < Addresses.Length;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Connect0()
- {
- try
- {
- Connect();
- }
- catch (UnknownHostException uhe)
- {
- throw new SmbException("Failed to connect to server", uhe);
- }
- catch (SmbException se)
- {
- throw;
- }
- catch (IOException ioe)
- {
- throw new SmbException("Failed to connect to server", ioe);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual void DoConnect()
- {
- SmbTransport trans;
- UniAddress addr;
- addr = GetAddress();
-
- if (Tree != null && Tree.Session.transport.Address.Equals(addr))
- {
- trans = Tree.Session.transport;
- }
- else
- {
- trans = SmbTransport.GetSmbTransport(addr, Url.Port);
- Tree = trans.GetSmbSession(Auth).GetSmbTree(_share, null);
- }
-
-
- string hostName = GetServerWithDfs();
- if (_enableDfs)
- {
- Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
- }
- if (Tree.InDomainDfs)
- {
- Tree.ConnectionState = 2;
- }
- try
- {
- if (Log.Level >= 3)
- {
- Log.WriteLine("doConnect: " + addr);
- }
- Tree.TreeConnect(null, null);
- }
- catch (SmbAuthException sae)
- {
- NtlmPasswordAuthentication a;
- SmbSession ssn;
- if (_share == null)
- {
- // IPC$ - try "anonymous" credentials
- ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Null);
- Tree = ssn.GetSmbTree(null, null);
- Tree.TreeConnect(null, null);
- }
- else
- {
- if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae)
- ) != null)
- {
- Auth = a;
- ssn = trans.GetSmbSession(Auth);
- Tree = ssn.GetSmbTree(_share, null);
- Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
- if (Tree.InDomainDfs)
- {
- Tree.ConnectionState = 2;
- }
- Tree.TreeConnect(null, null);
- }
- else
- {
- if (Log.Level >= 1 && HasNextAddress())
- {
- Runtime.PrintStackTrace(sae, Log);
- }
- throw;
- }
- }
- }
- }
-
- /// <summary>It is not necessary to call this method directly.</summary>
- /// <remarks>
- /// It is not necessary to call this method directly. This is the
- /// <tt>URLConnection</tt> implementation of <tt>connect()</tt>.
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public void Connect()
- {
- SmbTransport trans;
- SmbSession ssn;
- UniAddress addr;
- if (IsConnected())
- {
- return;
- }
- GetUncPath0();
- GetFirstAddress();
- for (; ; )
- {
- try
- {
- DoConnect();
- return;
- }
- catch (SmbAuthException sae)
- {
- throw;
- }
- catch (SmbException se)
- {
- // Prevents account lockout on servers with multiple IPs
- if (GetNextAddress() == null)
- {
- throw;
- }
- else
- {
- RemoveCurrentAddress();
- }
-
- if (Log.Level >= 3)
- {
- Runtime.PrintStackTrace(se, Log);
- }
- }
- }
- }
-
- internal virtual bool IsConnected()
- {
- return Tree != null && Tree.ConnectionState == 2;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual int Open0(int flags, int access, int attrs, int options)
- {
- int f;
- Connect0();
- if (Log.Level >= 3)
- {
- Log.WriteLine("open0: " + Unc);
- }
- if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
- {
- SmbComNtCreateAndXResponse response = new SmbComNtCreateAndXResponse();
- SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc, flags, access, _shareAccess
- , attrs, options, null);
- if (this is SmbNamedPipe)
- {
- request.Flags0 |= 0x16;
- request.DesiredAccess |= 0x20000;
- response.IsExtended = true;
- }
- Send(request, response);
- f = response.Fid;
- _attributes = response.ExtFileAttributes & AttrGetMask;
- _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- _isExists = true;
- }
- else
- {
- SmbComOpenAndXResponse response = new SmbComOpenAndXResponse();
- Send(new SmbComOpenAndX(Unc, access, flags, null), response);
- f = response.Fid;
- }
- return f;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Open(int flags, int access, int attrs, int options)
- {
- if (IsOpen())
- {
- return;
- }
- Fid = Open0(flags, access, attrs, options);
- Opened = true;
- TreeNum = Tree.TreeNum;
- }
-
- internal virtual bool IsOpen()
- {
- bool ans = Opened && IsConnected() && TreeNum == Tree.TreeNum;
- return ans;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Close(int f, long lastWriteTime)
- {
- if (Log.Level >= 3)
- {
- Log.WriteLine("close: " + f);
- }
- Send(new SmbComClose(f, lastWriteTime), Blank_resp());
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Close(long lastWriteTime)
- {
- if (IsOpen() == false)
- {
- return;
- }
- Close(Fid, lastWriteTime);
- Opened = false;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Close()
- {
- Close(0L);
- }
-
- /// <summary>
- /// Returns the <tt>NtlmPasswordAuthentication</tt> object used as
- /// credentials with this file or pipe.
- /// </summary>
- /// <remarks>
- /// Returns the <tt>NtlmPasswordAuthentication</tt> object used as
- /// credentials with this file or pipe. This can be used to retrieve the
- /// username for example:
- /// <tt>
- /// String username = f.getPrincipal().getName();
- /// </tt>
- /// The <tt>Principal</tt> object returned will never be <tt>null</tt>
- /// however the username can be <tt>null</tt> indication anonymous
- /// credentials were used (e.g. some IPC$ services).
- /// </remarks>
- public virtual Principal GetPrincipal()
- {
- return Auth;
- }
-
- /// <summary>Returns the last component of the target URL.</summary>
- /// <remarks>
- /// Returns the last component of the target URL. This will
- /// effectively be the name of the file or directory represented by this
- /// <code>SmbFile</code> or in the case of URLs that only specify a server
- /// or workgroup, the server or workgroup will be returned. The name of
- /// the root URL <code>smb://</code> is also <code>smb://</code>. If this
- /// <tt>SmbFile</tt> refers to a workgroup, server, share, or directory,
- /// the name will include a trailing slash '/' so that composing new
- /// <tt>SmbFile</tt>s will maintain the trailing slash requirement.
- /// </remarks>
- /// <returns>
- /// The last component of the URL associated with this SMB
- /// resource or <code>smb://</code> if the resource is <code>smb://</code>
- /// itself.
- /// </returns>
- public virtual string GetName()
- {
- GetUncPath0();
- if (_canon.Length > 1)
- {
- int i = _canon.Length - 2;
- while (_canon[i] != '/')
- {
- i--;
- }
- return Runtime.Substring(_canon, i + 1);
- }
- if (_share != null)
- {
- return _share + '/';
- }
- if (Url.GetHost().Length > 0)
- {
- return Url.GetHost() + '/';
- }
- return "smb://";
- }
-
- /// <summary>
- /// Everything but the last component of the URL representing this SMB
- /// resource is effectivly it's parent.
- /// </summary>
- /// <remarks>
- /// Everything but the last component of the URL representing this SMB
- /// resource is effectivly it's parent. The root URL <code>smb://</code>
- /// does not have a parent. In this case <code>smb://</code> is returned.
- /// </remarks>
- /// <returns>
- /// The parent directory of this SMB resource or
- /// <code>smb://</code> if the resource refers to the root of the URL
- /// hierarchy which incedentally is also <code>smb://</code>.
- /// </returns>
- public virtual string GetParent()
- {
- string str = Url.Authority;
- if (str.Length > 0)
- {
- StringBuilder sb = new StringBuilder("smb://");
- sb.Append(str);
- GetUncPath0();
- if (_canon.Length > 1)
- {
- sb.Append(_canon);
- }
- else
- {
- sb.Append('/');
- }
- str = sb.ToString();
- int i = str.Length - 2;
- while (str[i] != '/')
- {
- i--;
- }
- return Runtime.Substring(str, 0, i + 1);
- }
- return "smb://";
- }
-
- /// <summary>Returns the full uncanonicalized URL of this SMB resource.</summary>
- /// <remarks>
- /// Returns the full uncanonicalized URL of this SMB resource. An
- /// <code>SmbFile</code> constructed with the result of this method will
- /// result in an <code>SmbFile</code> that is equal to the original.
- /// </remarks>
- /// <returns>The uncanonicalized full URL of this SMB resource.</returns>
- public virtual string GetPath()
- {
- return Url.ToString();
- }
-
- internal virtual string GetUncPath0()
- {
- if (Unc == null)
- {
- char[] instr = Url.LocalPath.ToCharArray();
- char[] outstr = new char[instr.Length];
- int length = instr.Length;
- int i;
- int o;
- int state;
-
- state = 0;
- o = 0;
- for (i = 0; i < length; i++)
- {
- switch (state)
- {
- case 0:
- {
- if (instr[i] != '/')
- {
- return null;
- }
- outstr[o++] = instr[i];
- state = 1;
- break;
- }
-
- case 1:
- {
- if (instr[i] == '/')
- {
- break;
- }
- if (instr[i] == '.' && ((i + 1) >= length || instr[i + 1] == '/'))
- {
- i++;
- break;
- }
- if ((i + 1) < length && instr[i] == '.' && instr[i + 1] == '.' && ((i + 2) >= length
- || instr[i + 2] == '/'))
- {
- i += 2;
- if (o == 1)
- {
- break;
- }
- do
- {
- o--;
- }
- while (o > 1 && outstr[o - 1] != '/');
- break;
- }
- state = 2;
- goto case 2;
- }
-
- case 2:
- {
- if (instr[i] == '/')
- {
- state = 1;
- }
- outstr[o++] = instr[i];
- break;
- }
- }
- }
- _canon = new string(outstr, 0, o);
- if (o > 1)
- {
- o--;
- i = _canon.IndexOf('/', 1);
- if (i < 0)
- {
- _share = Runtime.Substring(_canon, 1);
- Unc = "\\";
- }
- else
- {
- if (i == o)
- {
- _share = Runtime.Substring(_canon, 1, i);
- Unc = "\\";
- }
- else
- {
- _share = Runtime.Substring(_canon, 1, i);
- Unc = Runtime.Substring(_canon, i, outstr[o] == '/' ? o : o + 1);
- Unc = Unc.Replace('/', '\\');
- }
- }
- }
- else
- {
- _share = null;
- Unc = "\\";
- }
- }
- return Unc;
- }
-
- /// <summary>Retuns the Windows UNC style path with backslashs intead of forward slashes.
- /// </summary>
- /// <remarks>Retuns the Windows UNC style path with backslashs intead of forward slashes.
- /// </remarks>
- /// <returns>The UNC path.</returns>
- public virtual string GetUncPath()
- {
- GetUncPath0();
- if (_share == null)
- {
- return "\\\\" + Url.GetHost();
- }
- return "\\\\" + Url.GetHost() + _canon.Replace('/', '\\');
- }
-
- /// <summary>
- /// Returns the full URL of this SMB resource with '.' and '..' components
- /// factored out.
- /// </summary>
- /// <remarks>
- /// Returns the full URL of this SMB resource with '.' and '..' components
- /// factored out. An <code>SmbFile</code> constructed with the result of
- /// this method will result in an <code>SmbFile</code> that is equal to
- /// the original.
- /// </remarks>
- /// <returns>The canonicalized URL of this SMB resource.</returns>
- public virtual string GetCanonicalPath()
- {
- string str = Url.Authority;
- GetUncPath0();
- if (str.Length > 0)
- {
- return "smb://" + Url.Authority + _canon;
- }
- return "smb://";
- }
-
- /// <summary>Retrieves the share associated with this SMB resource.</summary>
- /// <remarks>
- /// Retrieves the share associated with this SMB resource. In
- /// the case of <code>smb://</code>, <code>smb://workgroup/</code>,
- /// and <code>smb://server/</code> URLs which do not specify a share,
- /// <code>null</code> will be returned.
- /// </remarks>
- /// <returns>The share component or <code>null</code> if there is no share</returns>
- public virtual string GetShare()
- {
- return _share;
- }
-
- internal virtual string GetServerWithDfs()
- {
- if (_dfsReferral != null)
- {
- return _dfsReferral.Server;
- }
- return GetServer();
- }
-
- /// <summary>Retrieve the hostname of the server for this SMB resource.</summary>
- /// <remarks>
- /// Retrieve the hostname of the server for this SMB resource. If this
- /// <code>SmbFile</code> references a workgroup, the name of the workgroup
- /// is returned. If this <code>SmbFile</code> refers to the root of this
- /// SMB network hierarchy, <code>null</code> is returned.
- /// </remarks>
- /// <returns>
- /// The server or workgroup name or <code>null</code> if this
- /// <code>SmbFile</code> refers to the root <code>smb://</code> resource.
- /// </returns>
- public virtual string GetServer()
- {
- string str = Url.GetHost();
- if (str.Length == 0)
- {
- return null;
- }
- return str;
- }
-
- /// <summary>Returns type of of object this <tt>SmbFile</tt> represents.</summary>
- /// <remarks>Returns type of of object this <tt>SmbFile</tt> represents.</remarks>
- /// <returns>
- /// <tt>TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE,
- /// TYPE_PRINTER, TYPE_NAMED_PIPE</tt>, or <tt>TYPE_COMM</tt>.
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public new virtual int GetType()
- {
- if (Type == 0)
- {
- if (GetUncPath0().Length > 1)
- {
- Type = TypeFilesystem;
- }
- else
- {
- if (_share != null)
- {
- // treeConnect good enough to test service type
- Connect0();
- if (_share.Equals("IPC$"))
- {
- Type = TypeNamedPipe;
- }
- else
- {
- if (Tree.Service.Equals("LPT1:"))
- {
- Type = TypePrinter;
- }
- else
- {
- if (Tree.Service.Equals("COMM"))
- {
- Type = TypeComm;
- }
- else
- {
- Type = TypeShare;
- }
- }
- }
- }
- else
- {
- if (string.IsNullOrEmpty(Url.Authority))
- {
- Type = TypeWorkgroup;
- }
- else
- {
- UniAddress addr;
- try
- {
- addr = GetAddress();
- }
- catch (UnknownHostException uhe)
- {
- throw new SmbException(Url.ToString(), uhe);
- }
- if (addr.GetAddress() is NbtAddress)
- {
- int code = ((NbtAddress)addr.GetAddress()).GetNameType();
- if (code == 0x1d || code == 0x1b)
- {
- Type = TypeWorkgroup;
- return Type;
- }
- }
- Type = TypeServer;
- }
- }
- }
- }
- return Type;
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal virtual bool IsWorkgroup0()
- {
- if (Type == TypeWorkgroup || Url.GetHost().Length == 0)
- {
- Type = TypeWorkgroup;
- return true;
- }
- GetUncPath0();
- if (_share == null)
- {
- UniAddress addr = GetAddress();
- if (addr.GetAddress() is NbtAddress)
- {
- int code = ((NbtAddress)addr.GetAddress()).GetNameType();
- if (code == 0x1d || code == 0x1b)
- {
- Type = TypeWorkgroup;
- return true;
- }
- }
- Type = TypeServer;
- }
- return false;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual IInfo QueryPath(string path, int infoLevel)
- {
- Connect0();
- if (Log.Level >= 3)
- {
- Log.WriteLine("queryPath: " + path);
- }
- if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
- {
- Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse
- (infoLevel);
- Send(new Trans2QueryPathInformation(path, infoLevel), response);
- return response.Info;
- }
- else
- {
- SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(Tree
- .Session.transport.Server.ServerTimeZone * 1000 * 60L);
- Send(new SmbComQueryInformation(path), response);
- return response;
- }
- }
-
- /// <summary>Tests to see if the SMB resource exists.</summary>
- /// <remarks>
- /// Tests to see if the SMB resource exists. If the resource refers
- /// only to a server, this method determines if the server exists on the
- /// network and is advertising SMB services. If this resource refers to
- /// a workgroup, this method determines if the workgroup name is valid on
- /// the local SMB network. If this <code>SmbFile</code> refers to the root
- /// <code>smb://</code> resource <code>true</code> is always returned. If
- /// this <code>SmbFile</code> is a traditional file or directory, it will
- /// be queried for on the specified server as expected.
- /// </remarks>
- /// <returns>
- /// <code>true</code> if the resource exists or is alive or
- /// <code>false</code> otherwise
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool Exists()
- {
- if (_attrExpiration > Runtime.CurrentTimeMillis())
- {
- return _isExists;
- }
- _attributes = AttrReadonly | AttrDirectory;
- _createTime = 0L;
- _lastModified = 0L;
- _isExists = false;
- try
- {
- if (Url.GetHost().Length == 0)
- {
- }
- else
- {
- if (_share == null)
- {
- if (GetType() == TypeWorkgroup)
- {
- UniAddress.GetByName(Url.GetHost(), true);
- }
- else
- {
- UniAddress.GetByName(Url.GetHost()).GetHostName();
- }
- }
- else
- {
- if (GetUncPath0().Length == 1 || Runtime.EqualsIgnoreCase(_share, "IPC$"))
- {
- Connect0();
- }
- else
- {
- // treeConnect is good enough
- IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
- );
- _attributes = info.GetAttributes();
- _createTime = info.GetCreateTime();
- _lastModified = info.GetLastWriteTime();
- }
- }
- }
- _isExists = true;
- }
- catch (UnknownHostException)
- {
- }
- catch (SmbException se)
- {
- switch (se.GetNtStatus())
- {
- case NtStatus.NtStatusNoSuchFile:
- case NtStatus.NtStatusObjectNameInvalid:
- case NtStatus.NtStatusObjectNameNotFound:
- case NtStatus.NtStatusObjectPathNotFound:
- {
- break;
- }
-
- default:
- {
- throw;
- }
- }
- }
- _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- return _isExists;
- }
-
- /// <summary>
- /// Tests to see if the file this <code>SmbFile</code> represents can be
- /// read.
- /// </summary>
- /// <remarks>
- /// Tests to see if the file this <code>SmbFile</code> represents can be
- /// read. Because any file, directory, or other resource can be read if it
- /// exists, this method simply calls the <code>exists</code> method.
- /// </remarks>
- /// <returns><code>true</code> if the file is read-only</returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool CanRead()
- {
- if (GetType() == TypeNamedPipe)
- {
- // try opening the pipe for reading?
- return true;
- }
- return Exists();
- }
-
- // try opening and catch sharing violation?
- /// <summary>
- /// Tests to see if the file this <code>SmbFile</code> represents
- /// exists and is not marked read-only.
- /// </summary>
- /// <remarks>
- /// Tests to see if the file this <code>SmbFile</code> represents
- /// exists and is not marked read-only. By default, resources are
- /// considered to be read-only and therefore for <code>smb://</code>,
- /// <code>smb://workgroup/</code>, and <code>smb://server/</code> resources
- /// will be read-only.
- /// </remarks>
- /// <returns>
- /// <code>true</code> if the resource exists is not marked
- /// read-only
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool CanWrite()
- {
- if (GetType() == TypeNamedPipe)
- {
- // try opening the pipe for writing?
- return true;
- }
- return Exists() && (_attributes & AttrReadonly) == 0;
- }
-
- /// <summary>Tests to see if the file this <code>SmbFile</code> represents is a directory.
- /// </summary>
- /// <remarks>Tests to see if the file this <code>SmbFile</code> represents is a directory.
- /// </remarks>
- /// <returns><code>true</code> if this <code>SmbFile</code> is a directory</returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool IsDirectory()
- {
- if (GetUncPath0().Length == 1)
- {
- return true;
- }
- if (!Exists())
- {
- return false;
- }
- return (_attributes & AttrDirectory) == AttrDirectory;
- }
-
- /// <summary>Tests to see if the file this <code>SmbFile</code> represents is not a directory.
- /// </summary>
- /// <remarks>Tests to see if the file this <code>SmbFile</code> represents is not a directory.
- /// </remarks>
- /// <returns><code>true</code> if this <code>SmbFile</code> is not a directory</returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool IsFile()
- {
- if (GetUncPath0().Length == 1)
- {
- return false;
- }
- Exists();
- return (_attributes & AttrDirectory) == 0;
- }
-
- /// <summary>
- /// Tests to see if the file this SmbFile represents is marked as
- /// hidden.
- /// </summary>
- /// <remarks>
- /// Tests to see if the file this SmbFile represents is marked as
- /// hidden. This method will also return true for shares with names that
- /// end with '$' such as <code>IPC$</code> or <code>C$</code>.
- /// </remarks>
- /// <returns><code>true</code> if the <code>SmbFile</code> is marked as being hidden</returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual bool IsHidden()
- {
- if (_share == null)
- {
- return false;
- }
- if (GetUncPath0().Length == 1)
- {
- if (_share.EndsWith("$"))
- {
- return true;
- }
- return false;
- }
- Exists();
- return (_attributes & AttrHidden) == AttrHidden;
- }
-
- /// <summary>
- /// If the path of this <code>SmbFile</code> falls within a DFS volume,
- /// this method will return the referral path to which it maps.
- /// </summary>
- /// <remarks>
- /// If the path of this <code>SmbFile</code> falls within a DFS volume,
- /// this method will return the referral path to which it maps. Otherwise
- /// <code>null</code> is returned.
- /// </remarks>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual string GetDfsPath()
- {
- ResolveDfs(null);
- if (_dfsReferral == null)
- {
- return null;
- }
- string path = "smb:/" + _dfsReferral.Server + "/" + _dfsReferral.Share + Unc;
- path = path.Replace('\\', '/');
- if (IsDirectory())
- {
- path += '/';
- }
- return path;
- }
-
- /// <summary>Retrieve the time this <code>SmbFile</code> was created.</summary>
- /// <remarks>
- /// Retrieve the time this <code>SmbFile</code> was created. The value
- /// returned is suitable for constructing a
- /// <see cref="System.DateTime">System.DateTime</see>
- /// object
- /// (i.e. seconds since Epoch 1970). Times should be the same as those
- /// reported using the properties dialog of the Windows Explorer program.
- /// For Win95/98/Me this is actually the last write time. It is currently
- /// not possible to retrieve the create time from files on these systems.
- /// </remarks>
- /// <returns>
- /// The number of milliseconds since the 00:00:00 GMT, January 1,
- /// 1970 as a <code>long</code> value
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long CreateTime()
- {
- if (GetUncPath0().Length > 1)
- {
- Exists();
- return _createTime;
- }
- return 0L;
- }
-
- /// <summary>
- /// Retrieve the last time the file represented by this
- /// <code>SmbFile</code> was modified.
- /// </summary>
- /// <remarks>
- /// Retrieve the last time the file represented by this
- /// <code>SmbFile</code> was modified. The value returned is suitable for
- /// constructing a
- /// <see cref="System.DateTime">System.DateTime</see>
- /// object (i.e. seconds since Epoch
- /// 1970). Times should be the same as those reported using the properties
- /// dialog of the Windows Explorer program.
- /// </remarks>
- /// <returns>
- /// The number of milliseconds since the 00:00:00 GMT, January 1,
- /// 1970 as a <code>long</code> value
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long LastModified()
- {
- if (GetUncPath0().Length > 1)
- {
- Exists();
- return _lastModified;
- }
- return 0L;
- }
-
- /// <summary>List the contents of this SMB resource.</summary>
- /// <remarks>
- /// List the contents of this SMB resource. The list returned by this
- /// method will be;
- /// <ul>
- /// <li> files and directories contained within this resource if the
- /// resource is a normal disk file directory,
- /// <li> all available NetBIOS workgroups or domains if this resource is
- /// the top level URL <code>smb://</code>,
- /// <li> all servers registered as members of a NetBIOS workgroup if this
- /// resource refers to a workgroup in a <code>smb://workgroup/</code> URL,
- /// <li> all browseable shares of a server including printers, IPC
- /// services, or disk volumes if this resource is a server URL in the form
- /// <code>smb://server/</code>,
- /// <li> or <code>null</code> if the resource cannot be resolved.
- /// </ul>
- /// </remarks>
- /// <returns>
- /// A <code>String[]</code> array of files and directories,
- /// workgroups, servers, or shares depending on the context of the
- /// resource URL
- /// </returns>
- /// <exception cref="SmbException"></exception>
- public virtual string[] List()
- {
- return List("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
- }
-
- /// <summary>List the contents of this SMB resource.</summary>
- /// <remarks>
- /// List the contents of this SMB resource. The list returned will be
- /// identical to the list returned by the parameterless <code>list()</code>
- /// method minus filenames filtered by the specified filter.
- /// </remarks>
- /// <param name="filter">a filename filter to exclude filenames from the results</param>
- /// <exception cref="SmbException"># @return An array of filenames</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual string[] List(ISmbFilenameFilter filter)
- {
- return List("*", AttrDirectory | AttrHidden | AttrSystem, filter, null);
- }
-
- /// <summary>
- /// List the contents of this SMB resource as an array of
- /// <code>SmbFile</code> objects.
- /// </summary>
- /// <remarks>
- /// List the contents of this SMB resource as an array of
- /// <code>SmbFile</code> objects. This method is much more efficient than
- /// the regular <code>list</code> method when querying attributes of each
- /// file in the result set.
- /// <p>
- /// The list of <code>SmbFile</code>s returned by this method will be;
- /// <ul>
- /// <li> files and directories contained within this resource if the
- /// resource is a normal disk file directory,
- /// <li> all available NetBIOS workgroups or domains if this resource is
- /// the top level URL <code>smb://</code>,
- /// <li> all servers registered as members of a NetBIOS workgroup if this
- /// resource refers to a workgroup in a <code>smb://workgroup/</code> URL,
- /// <li> all browseable shares of a server including printers, IPC
- /// services, or disk volumes if this resource is a server URL in the form
- /// <code>smb://server/</code>,
- /// <li> or <code>null</code> if the resource cannot be resolved.
- /// </ul>
- /// </remarks>
- /// <returns>
- /// An array of <code>SmbFile</code> objects representing file
- /// and directories, workgroups, servers, or shares depending on the context
- /// of the resource URL
- /// </returns>
- /// <exception cref="SmbException"></exception>
- public virtual SmbFile[] ListFiles()
- {
- return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
- }
-
- /// <summary>
- /// The CIFS protocol provides for DOS "wildcards" to be used as
- /// a performance enhancement.
- /// </summary>
- /// <remarks>
- /// The CIFS protocol provides for DOS "wildcards" to be used as
- /// a performance enhancement. The client does not have to filter
- /// the names and the server does not have to return all directory
- /// entries.
- /// <p>
- /// The wildcard expression may consist of two special meta
- /// characters in addition to the normal filename characters. The '*'
- /// character matches any number of characters in part of a name. If
- /// the expression begins with one or more '?'s then exactly that
- /// many characters will be matched whereas if it ends with '?'s
- /// it will match that many characters <i>or less</i>.
- /// <p>
- /// Wildcard expressions will not filter workgroup names or server names.
- /// <blockquote><pre>
- /// winnt&gt; ls c?o
- /// clock.avi -rw-- 82944 Mon Oct 14 1996 1:38 AM
- /// Cookies drw-- 0 Fri Nov 13 1998 9:42 PM
- /// 2 items in 5ms
- /// </pre></blockquote>
- /// </remarks>
- /// <param name="wildcard">a wildcard expression</param>
- /// <exception cref="SmbException">SmbException</exception>
- /// <returns>
- /// An array of <code>SmbFile</code> objects representing file
- /// and directories, workgroups, servers, or shares depending on the context
- /// of the resource URL
- /// </returns>
- /// <exception cref="SmbException"></exception>
- public virtual SmbFile[] ListFiles(string wildcard)
- {
- return ListFiles(wildcard, AttrDirectory | AttrHidden | AttrSystem, null, null
- );
- }
-
- /// <summary>List the contents of this SMB resource.</summary>
- /// <remarks>
- /// List the contents of this SMB resource. The list returned will be
- /// identical to the list returned by the parameterless <code>listFiles()</code>
- /// method minus files filtered by the specified filename filter.
- /// </remarks>
- /// <param name="filter">a filter to exclude files from the results</param>
- /// <returns>An array of <tt>SmbFile</tt> objects</returns>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual SmbFile[] ListFiles(ISmbFilenameFilter filter)
- {
- return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, filter, null);
- }
-
- /// <summary>List the contents of this SMB resource.</summary>
- /// <remarks>
- /// List the contents of this SMB resource. The list returned will be
- /// identical to the list returned by the parameterless <code>listFiles()</code>
- /// method minus filenames filtered by the specified filter.
- /// </remarks>
- /// <param name="filter">a file filter to exclude files from the results</param>
- /// <returns>An array of <tt>SmbFile</tt> objects</returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual SmbFile[] ListFiles(ISmbFileFilter filter)
- {
- return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, filter);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual string[] List(string wildcard, int searchAttributes, ISmbFilenameFilter
- fnf, ISmbFileFilter ff)
- {
- List<object> list = new List<object>();
- DoEnum(list, false, wildcard, searchAttributes, fnf, ff);
-
- return Collections.ToArray<string>(list); //Collections.ToArray<string>(list);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual SmbFile[] ListFiles(string wildcard, int searchAttributes
- , ISmbFilenameFilter fnf, ISmbFileFilter ff)
- {
- List<object> list = new List<object>();
- DoEnum(list, true, wildcard, searchAttributes, fnf, ff);
-
- return Collections.ToArray<SmbFile>(list); //Collections.ToArray<SmbFile>(list);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void DoEnum(List<object> list, bool files, string wildcard, int searchAttributes
- , ISmbFilenameFilter fnf, ISmbFileFilter ff)
- {
- if (ff != null && ff is DosFileFilter)
- {
- DosFileFilter dff = (DosFileFilter)ff;
- if (dff.Wildcard != null)
- {
- wildcard = dff.Wildcard;
- }
- searchAttributes = dff.Attributes;
- }
- try
- {
- int hostlen = Url.GetHost() != null ? Url.GetHost().Length : 0;
- if (hostlen == 0 || GetType() == TypeWorkgroup)
- {
- DoNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff);
- }
- else
- {
- if (_share == null)
- {
- DoShareEnum(list, files, wildcard, searchAttributes, fnf, ff);
- }
- else
- {
- DoFindFirstNext(list, files, wildcard, searchAttributes, fnf, ff);
- }
- }
- }
- catch (UnknownHostException uhe)
- {
- throw new SmbException(Url.ToString(), uhe);
- }
- catch (UriFormatException mue)
- {
- throw new SmbException(Url.ToString(), mue);
- }
- }
-
- private void RemoveCurrentAddress()
- {
- if (AddressIndex >= 1)
- {
- UniAddress[] aux = new UniAddress[Addresses.Length - 1];
-
- Array.Copy(Addresses, 1, aux, 0, Addresses.Length - 1);
-
- Addresses = aux;
- AddressIndex--;
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- internal virtual void DoShareEnum(List<object> list, bool files, string wildcard, int
- searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
- {
- string p = Url.AbsolutePath;
- IOException last = null;
- IFileEntry[] entries;
- UniAddress addr;
- IFileEntry e;
- Hashtable map;
- if (p.LastIndexOf('/') != (p.Length - 1))
- {
- throw new SmbException(Url + " directory must end with '/'");
- }
- if (GetType() != TypeServer)
- {
- throw new SmbException("The requested list operations is invalid: " + Url);
- }
- map = new Hashtable();
- if (_enableDfs && Dfs.IsTrustedDomain(GetServer(), Auth))
- {
- try
- {
- entries = DoDfsRootEnum();
- for (int ei = 0; ei < entries.Length; ei++)
- {
- e = entries[ei];
- if (map.ContainsKey(e) == false)
- {
- map.Put(e, e);
- }
- }
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 4)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- }
- }
- addr = GetFirstAddress();
- while (addr != null)
- {
- try
- {
- last = null;
-
- DoConnect();
- try
- {
- entries = DoMsrpcShareEnum();
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 3)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- entries = DoNetShareEnum();
- }
- for (int ei = 0; ei < entries.Length; ei++)
- {
- e = entries[ei];
- if (map.ContainsKey(e) == false)
- {
- map.Put(e, e);
- }
- }
- break;
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 3)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- last = ioe;
-
- if (!(ioe is SmbAuthException))
- {
- RemoveCurrentAddress();
-
- addr = GetNextAddress();
- }
- else
- {
- break;
- }
- }
-
- }
- if (last != null && map.Count == 0)
- {
- if (last is SmbException == false)
- {
- throw new SmbException(Url.ToString(), last);
- }
- throw (SmbException)last;
- }
- //Iterator iter = map.Keys.Iterator();
- //while (iter.HasNext())
- foreach (var item in map.Keys)
- {
- e = (IFileEntry)item;
- string name = e.GetName();
- if (fnf != null && fnf.Accept(this, name) == false)
- {
- continue;
- }
- if (name.Length > 0)
- {
- // if !files we don't need to create SmbFiles here
- SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
- | AttrDirectory, 0L, 0L, 0L);
- if (ff != null && ff.Accept(f) == false)
- {
- continue;
- }
- if (files)
- {
- list.Add(f);
- }
- else
- {
- list.Add(name);
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual IFileEntry[] DoDfsRootEnum()
- {
- MsrpcDfsRootEnum rpc;
- DcerpcHandle handle = null;
- IFileEntry[] entries;
- handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\netdfs]"
- , Auth);
- try
- {
- rpc = new MsrpcDfsRootEnum(GetServer());
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, true);
- }
- return rpc.GetEntries();
- }
- finally
- {
- try
- {
- handle.Close();
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 4)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual IFileEntry[] DoMsrpcShareEnum()
- {
- MsrpcShareEnum rpc;
- DcerpcHandle handle;
- rpc = new MsrpcShareEnum(Url.GetHost());
- handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\srvsvc]"
- , Auth);
- try
- {
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, true);
- }
- return rpc.GetEntries();
- }
- finally
- {
- try
- {
- handle.Close();
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 4)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual IFileEntry[] DoNetShareEnum()
- {
- SmbComTransaction req = new NetShareEnum();
- SmbComTransactionResponse resp = new NetShareEnumResponse();
- Send(req, resp);
- if (resp.Status != WinError.ErrorSuccess)
- {
- throw new SmbException(resp.Status, true);
- }
- return resp.Results;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- internal virtual void DoNetServerEnum(List<object> list, bool files, string wildcard
- , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
- {
- int listType = Url.GetHost().Length == 0 ? 0 : GetType();
- SmbComTransaction req;
- SmbComTransactionResponse resp;
- if (listType == 0)
- {
- Connect0();
- req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName, NetServerEnum2
- .SvTypeDomainEnum);
- resp = new NetServerEnum2Response();
- }
- else
- {
- if (listType == TypeWorkgroup)
- {
- req = new NetServerEnum2(Url.GetHost(), NetServerEnum2.SvTypeAll);
- resp = new NetServerEnum2Response();
- }
- else
- {
- throw new SmbException("The requested list operations is invalid: " + Url);
- }
- }
- bool more;
- do
- {
- int n;
- Send(req, resp);
- if (resp.Status != WinError.ErrorSuccess && resp.Status != WinError.ErrorMoreData)
- {
- throw new SmbException(resp.Status, true);
- }
- more = resp.Status == WinError.ErrorMoreData;
- n = more ? resp.NumEntries - 1 : resp.NumEntries;
- for (int i = 0; i < n; i++)
- {
- IFileEntry e = resp.Results[i];
- string name = e.GetName();
- if (fnf != null && fnf.Accept(this, name) == false)
- {
- continue;
- }
- if (name.Length > 0)
- {
- // if !files we don't need to create SmbFiles here
- SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
- | AttrDirectory, 0L, 0L, 0L);
- if (ff != null && ff.Accept(f) == false)
- {
- continue;
- }
- if (files)
- {
- list.Add(f);
- }
- else
- {
- list.Add(name);
- }
- }
- }
- if (GetType() != TypeWorkgroup)
- {
- break;
- }
- req.SubCommand = unchecked(SmbComTransaction.NetServerEnum3);
- req.Reset(0, ((NetServerEnum2Response)resp).LastName);
- resp.Reset();
- }
- while (more);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- internal virtual void DoFindFirstNext(List<object> list, bool files, string wildcard
- , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
- {
- SmbComTransaction req;
- Trans2FindFirst2Response resp;
- int sid;
- string path = GetUncPath0();
- string p = Url.AbsolutePath;
- if (p.LastIndexOf('/') != (p.Length - 1))
- {
- throw new SmbException(Url + " directory must end with '/'");
- }
- req = new Trans2FindFirst2(path, wildcard, searchAttributes);
- resp = new Trans2FindFirst2Response();
- if (Log.Level >= 3)
- {
- Log.WriteLine("doFindFirstNext: " + req.Path);
- }
- Send(req, resp);
- sid = resp.Sid;
- req = new Trans2FindNext2(sid, resp.ResumeKey, resp.LastName);
- resp.SubCommand = SmbComTransaction.Trans2FindNext2;
- for (; ; )
- {
- for (int i = 0; i < resp.NumEntries; i++)
- {
- IFileEntry e = resp.Results[i];
- string name = e.GetName();
- if (name.Length < 3)
- {
- int h = name.GetHashCode();
- if (h == HashDot || h == HashDotDot)
- {
- if (name.Equals(".") || name.Equals(".."))
- {
- continue;
- }
- }
- }
- if (fnf != null && fnf.Accept(this, name) == false)
- {
- continue;
- }
- if (name.Length > 0)
- {
- SmbFile f = new SmbFile(this, name, TypeFilesystem, e.GetAttributes
- (), e.CreateTime(), e.LastModified(), e.Length());
- if (ff != null && ff.Accept(f) == false)
- {
- continue;
- }
- if (files)
- {
- list.Add(f);
- }
- else
- {
- list.Add(name);
- }
- }
- }
- if (resp.IsEndOfSearch || resp.NumEntries == 0)
- {
- break;
- }
- req.Reset(resp.ResumeKey, resp.LastName);
- resp.Reset();
- Send(req, resp);
- }
- try
- {
- Send(new SmbComFindClose2(sid), Blank_resp());
- }
- catch (SmbException se)
- {
- if (Log.Level >= 4)
- {
- Runtime.PrintStackTrace(se, Log);
- }
- }
- }
-
- /// <summary>
- /// Changes the name of the file this <code>SmbFile</code> represents to the name
- /// designated by the <code>SmbFile</code> argument.
- /// </summary>
- /// <remarks>
- /// Changes the name of the file this <code>SmbFile</code> represents to the name
- /// designated by the <code>SmbFile</code> argument.
- /// <p/>
- /// <i>Remember: <code>SmbFile</code>s are immutible and therefore
- /// the path associated with this <code>SmbFile</code> object will not
- /// change). To access the renamed file it is necessary to construct a
- /// new <tt>SmbFile</tt></i>.
- /// </remarks>
- /// <param name="dest">An <code>SmbFile</code> that represents the new pathname</param>
- /// <exception cref="System.ArgumentNullException">If the <code>dest</code> argument is <code>null</code>
- /// </exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void RenameTo(SmbFile dest)
- {
- if (GetUncPath0().Length == 1 || dest.GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- ResolveDfs(null);
- dest.ResolveDfs(null);
- if (!Tree.Equals(dest.Tree))
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- if (Log.Level >= 3)
- {
- Log.WriteLine("renameTo: " + Unc + " -> " + dest.Unc);
- }
- _attrExpiration = _sizeExpiration = 0;
- dest._attrExpiration = 0;
- Send(new SmbComRename(Unc, dest.Unc), Blank_resp());
- }
-
- internal class WriterThread : Thread
- {
- internal byte[] B;
-
- internal int N;
-
- internal long Off;
-
- internal bool Ready;
-
- internal SmbFile Dest;
-
- internal SmbException E;
-
- internal bool UseNtSmbs;
-
- internal SmbComWriteAndX Reqx;
-
- internal SmbComWrite Req;
-
- internal ServerMessageBlock Resp;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public WriterThread(SmbFile enclosing)
- : base("JCIFS-WriterThread")
- {
- this._enclosing = enclosing;
- UseNtSmbs = this._enclosing.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs);
- if (UseNtSmbs)
- {
- Reqx = new SmbComWriteAndX();
- Resp = new SmbComWriteAndXResponse();
- }
- else
- {
- Req = new SmbComWrite();
- Resp = new SmbComWriteResponse();
- }
- Ready = false;
- }
-
- internal virtual void Write(byte[] b, int n, SmbFile dest, long off)
- {
- lock (this)
- {
- this.B = b;
- this.N = n;
- this.Dest = dest;
- this.Off = off;
- Ready = false;
- Runtime.Notify(this);
- }
- }
-
- public override void Run()
- {
- lock (this)
- {
- try
- {
- for (; ; )
- {
- Runtime.Notify(this);
- Ready = true;
- while (Ready)
- {
- Runtime.Wait(this);
- }
- if (N == -1)
- {
- return;
- }
- if (UseNtSmbs)
- {
- Reqx.SetParam(Dest.Fid, Off, N, B, 0, N);
- Dest.Send(Reqx, Resp);
- }
- else
- {
- Req.SetParam(Dest.Fid, Off, N, B, 0, N);
- Dest.Send(Req, Resp);
- }
- }
- }
- catch (SmbException e)
- {
- this.E = e;
- }
- catch (Exception x)
- {
- E = new SmbException("WriterThread", x);
- }
- Runtime.Notify(this);
- }
- }
-
- private readonly SmbFile _enclosing;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void CopyTo0(SmbFile dest, byte[][] b, int bsize, WriterThread
- w, SmbComReadAndX req, SmbComReadAndXResponse resp)
- {
- int i;
- if (_attrExpiration < Runtime.CurrentTimeMillis())
- {
- _attributes = AttrReadonly | AttrDirectory;
- _createTime = 0L;
- _lastModified = 0L;
- _isExists = false;
- IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
- );
- _attributes = info.GetAttributes();
- _createTime = info.GetCreateTime();
- _lastModified = info.GetLastWriteTime();
- _isExists = true;
- _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- }
- if (IsDirectory())
- {
- SmbFile[] files;
- SmbFile ndest;
- string path = dest.GetUncPath0();
- if (path.Length > 1)
- {
- try
- {
- dest.Mkdir();
- dest.SetPathInformation(_attributes, _createTime, _lastModified);
- }
- catch (SmbException se)
- {
- if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied && se.GetNtStatus() != NtStatus
- .NtStatusObjectNameCollision)
- {
- throw;
- }
- }
- }
- files = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
- try
- {
- for (i = 0; i < files.Length; i++)
- {
- ndest = new SmbFile(dest, files[i].GetName(), files[i].Type, files[i]._attributes,
- files[i]._createTime, files[i]._lastModified, files[i]._size);
- files[i].CopyTo0(ndest, b, bsize, w, req, resp);
- }
- }
- catch (UnknownHostException uhe)
- {
- throw new SmbException(Url.ToString(), uhe);
- }
- catch (UriFormatException mue)
- {
- throw new SmbException(Url.ToString(), mue);
- }
- }
- else
- {
- long off;
- try
- {
- Open(ORdonly, 0, AttrNormal, 0);
- try
- {
- dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
- SmbConstants.FileWriteAttributes, _attributes, 0);
- }
- catch (SmbAuthException sae)
- {
- if ((dest._attributes & AttrReadonly) != 0)
- {
- dest.SetPathInformation(dest._attributes & ~AttrReadonly, 0L, 0L);
- dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
- SmbConstants.FileWriteAttributes, _attributes, 0);
- }
- else
- {
- throw;
- }
- }
- i = 0;
- off = 0L;
- for (; ; )
- {
- req.SetParam(Fid, off, bsize);
- resp.SetParam(b[i], 0);
- Send(req, resp);
- lock (w)
- {
- if (w.E != null)
- {
- throw w.E;
- }
- while (!w.Ready)
- {
- try
- {
- Runtime.Wait(w);
- }
- catch (Exception ie)
- {
- throw new SmbException(dest.Url.ToString(), ie);
- }
- }
- if (w.E != null)
- {
- throw w.E;
- }
- if (resp.DataLength <= 0)
- {
- break;
- }
- w.Write(b[i], resp.DataLength, dest, off);
- }
- i = i == 1 ? 0 : 1;
- off += resp.DataLength;
- }
- dest.Send(new Trans2SetFileInformation(dest.Fid, _attributes, _createTime, _lastModified
- ), new Trans2SetFileInformationResponse());
- dest.Close(0L);
- }
- catch (SmbException se)
- {
- if (IgnoreCopyToException == false)
- {
- throw new SmbException("Failed to copy file from [" + ToString() + "] to ["
- + dest + "]", se);
- }
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(se, Log);
- }
- }
- finally
- {
- Close();
- }
- }
- }
-
- /// <summary>
- /// This method will copy the file or directory represented by this
- /// <tt>SmbFile</tt> and it's sub-contents to the location specified by the
- /// <tt>dest</tt> parameter.
- /// </summary>
- /// <remarks>
- /// This method will copy the file or directory represented by this
- /// <tt>SmbFile</tt> and it's sub-contents to the location specified by the
- /// <tt>dest</tt> parameter. This file and the destination file do not
- /// need to be on the same host. This operation does not copy extended
- /// file attibutes such as ACLs but it does copy regular attributes as
- /// well as create and last write times. This method is almost twice as
- /// efficient as manually copying as it employs an additional write
- /// thread to read and write data concurrently.
- /// <p/>
- /// It is not possible (nor meaningful) to copy entire workgroups or
- /// servers.
- /// </remarks>
- /// <param name="dest">the destination file or directory</param>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void CopyTo(SmbFile dest)
- {
- SmbComReadAndX req;
- SmbComReadAndXResponse resp;
- WriterThread w;
- int bsize;
- byte[][] b;
- if (_share == null || dest._share == null)
- {
- throw new SmbException("Invalid operation for workgroups or servers");
- }
- req = new SmbComReadAndX();
- resp = new SmbComReadAndXResponse();
- Connect0();
- dest.Connect0();
- ResolveDfs(null);
- try
- {
- if (GetAddress().Equals(dest.GetAddress()) && _canon.RegionMatches(true, 0, dest._canon
- , 0, Math.Min(_canon.Length, dest._canon.Length)))
- {
- throw new SmbException("Source and destination paths overlap.");
- }
- }
- catch (UnknownHostException)
- {
- }
- w = new WriterThread(this);
- w.SetDaemon(true);
- w.Start();
- SmbTransport t1 = Tree.Session.transport;
- SmbTransport t2 = dest.Tree.Session.transport;
- if (t1.SndBufSize < t2.SndBufSize)
- {
- t2.SndBufSize = t1.SndBufSize;
- }
- else
- {
- t1.SndBufSize = t2.SndBufSize;
- }
- bsize = Math.Min(t1.RcvBufSize - 70, t1.SndBufSize - 70);
- b = new[] { new byte[bsize], new byte[bsize] };
- try
- {
- CopyTo0(dest, b, bsize, w, req, resp);
- }
- finally
- {
- w.Write(null, -1, null, 0);
- }
- }
-
- /// <summary>
- /// This method will delete the file or directory specified by this
- /// <code>SmbFile</code>.
- /// </summary>
- /// <remarks>
- /// This method will delete the file or directory specified by this
- /// <code>SmbFile</code>. If the target is a directory, the contents of
- /// the directory will be deleted as well. If a file within the directory or
- /// it's sub-directories is marked read-only, the read-only status will
- /// be removed and the file will be deleted.
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Delete()
- {
- Exists();
- GetUncPath0();
- Delete(Unc);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Delete(string fileName)
- {
- if (GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- if (Runtime.CurrentTimeMillis() > _attrExpiration)
- {
- _attributes = AttrReadonly | AttrDirectory;
- _createTime = 0L;
- _lastModified = 0L;
- _isExists = false;
- IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
- );
- _attributes = info.GetAttributes();
- _createTime = info.GetCreateTime();
- _lastModified = info.GetLastWriteTime();
- _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- _isExists = true;
- }
- if ((_attributes & AttrReadonly) != 0)
- {
- SetReadWrite();
- }
- if (Log.Level >= 3)
- {
- Log.WriteLine("delete: " + fileName);
- }
- if ((_attributes & AttrDirectory) != 0)
- {
- try
- {
- SmbFile[] l = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null
- );
- for (int i = 0; i < l.Length; i++)
- {
- l[i].Delete();
- }
- }
- catch (SmbException se)
- {
- if (se.GetNtStatus() != NtStatus.NtStatusNoSuchFile)
- {
- throw;
- }
- }
- Send(new SmbComDeleteDirectory(fileName), Blank_resp());
- }
- else
- {
- Send(new SmbComDelete(fileName), Blank_resp());
- }
- _attrExpiration = _sizeExpiration = 0;
- }
-
- /// <summary>Returns the length of this <tt>SmbFile</tt> in bytes.</summary>
- /// <remarks>
- /// Returns the length of this <tt>SmbFile</tt> in bytes. If this object
- /// is a <tt>TYPE_SHARE</tt> the total capacity of the disk shared in
- /// bytes is returned. If this object is a directory or a type other than
- /// <tt>TYPE_SHARE</tt>, 0L is returned.
- /// </remarks>
- /// <returns>
- /// The length of the file in bytes or 0 if this
- /// <code>SmbFile</code> is not a file.
- /// </returns>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long Length()
- {
- if (_sizeExpiration > Runtime.CurrentTimeMillis())
- {
- return _size;
- }
- if (GetType() == TypeShare)
- {
- Trans2QueryFsInformationResponse response;
- int level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION;
- response = new Trans2QueryFsInformationResponse(level);
- Send(new Trans2QueryFsInformation(level), response);
- _size = response.Info.GetCapacity();
- }
- else
- {
- if (GetUncPath0().Length > 1 && Type != TypeNamedPipe)
- {
- IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO
- );
- _size = info.GetSize();
- }
- else
- {
- _size = 0L;
- }
- }
- _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- return _size;
- }
-
- /// <summary>
- /// This method returns the free disk space in bytes of the drive this share
- /// represents or the drive on which the directory or file resides.
- /// </summary>
- /// <remarks>
- /// This method returns the free disk space in bytes of the drive this share
- /// represents or the drive on which the directory or file resides. Objects
- /// other than <tt>TYPE_SHARE</tt> or <tt>TYPE_FILESYSTEM</tt> will result
- /// in 0L being returned.
- /// </remarks>
- /// <returns>
- /// the free disk space in bytes of the drive on which this file or
- /// directory resides
- /// </returns>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long GetDiskFreeSpace()
- {
- if (GetType() == TypeShare || Type == TypeFilesystem)
- {
- int level = Trans2QueryFsInformationResponse.SmbFsFullSizeInformation;
- try
- {
- return QueryFsInformation(level);
- }
- catch (SmbException ex)
- {
- switch (ex.GetNtStatus())
- {
- case NtStatus.NtStatusInvalidInfoClass:
- case NtStatus.NtStatusUnsuccessful:
- {
- // NetApp Filer
- // SMB_FS_FULL_SIZE_INFORMATION not supported by the server.
- level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION;
- return QueryFsInformation(level);
- }
- }
- throw;
- }
- }
- return 0L;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- private long QueryFsInformation(int level)
- {
- Trans2QueryFsInformationResponse response;
- response = new Trans2QueryFsInformationResponse(level);
- Send(new Trans2QueryFsInformation(level), response);
- if (Type == TypeShare)
- {
- _size = response.Info.GetCapacity();
- _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
- }
- return response.Info.GetFree();
- }
-
- /// <summary>
- /// Creates a directory with the path specified by this
- /// <code>SmbFile</code>.
- /// </summary>
- /// <remarks>
- /// Creates a directory with the path specified by this
- /// <code>SmbFile</code>. For this method to be successful, the target
- /// must not already exist. This method will fail when
- /// used with <code>smb://</code>, <code>smb://workgroup/</code>,
- /// <code>smb://server/</code>, or <code>smb://server/share/</code> URLs
- /// because workgroups, servers, and shares cannot be dynamically created
- /// (although in the future it may be possible to create shares).
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Mkdir()
- {
- string path = GetUncPath0();
- if (path.Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- if (Log.Level >= 3)
- {
- Log.WriteLine("mkdir: " + path);
- }
- Send(new SmbComCreateDirectory(path), Blank_resp());
- _attrExpiration = _sizeExpiration = 0;
- }
-
- /// <summary>
- /// Creates a directory with the path specified by this <tt>SmbFile</tt>
- /// and any parent directories that do not exist.
- /// </summary>
- /// <remarks>
- /// Creates a directory with the path specified by this <tt>SmbFile</tt>
- /// and any parent directories that do not exist. This method will fail
- /// when used with <code>smb://</code>, <code>smb://workgroup/</code>,
- /// <code>smb://server/</code>, or <code>smb://server/share/</code> URLs
- /// because workgroups, servers, and shares cannot be dynamically created
- /// (although in the future it may be possible to create shares).
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Mkdirs()
- {
- SmbFile parent;
- try
- {
- parent = new SmbFile(GetParent(), Auth);
- }
- catch (IOException)
- {
- return;
- }
- if (parent.Exists() == false)
- {
- parent.Mkdirs();
- }
- Mkdir();
- }
-
- /// <summary>Create a new file but fail if it already exists.</summary>
- /// <remarks>
- /// Create a new file but fail if it already exists. The check for
- /// existance of the file and it's creation are an atomic operation with
- /// respect to other filesystem activities.
- /// </remarks>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void CreateNewFile()
- {
- if (GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- Close(Open0(ORdwr | OCreat | OExcl, 0, AttrNormal, 0), 0L);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void SetPathInformation(int attrs, long ctime, long mtime)
- {
- int f;
- int dir;
- Exists();
- dir = _attributes & AttrDirectory;
- f = Open0(ORdonly, SmbConstants.FileWriteAttributes, dir, dir != 0 ? 0x0001
- : 0x0040);
- Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), new Trans2SetFileInformationResponse
- ());
- Close(f, 0L);
- _attrExpiration = 0;
- }
-
- /// <summary>Set the create time of the file.</summary>
- /// <remarks>
- /// Set the create time of the file. The time is specified as milliseconds
- /// from Jan 1, 1970 which is the same as that which is returned by the
- /// <tt>createTime()</tt> method.
- /// <p/>
- /// This method does not apply to workgroups, servers, or shares.
- /// </remarks>
- /// <param name="time">the create time as milliseconds since Jan 1, 1970</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void SetCreateTime(long time)
- {
- if (GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- SetPathInformation(0, time, 0L);
- }
-
- /// <summary>Set the last modified time of the file.</summary>
- /// <remarks>
- /// Set the last modified time of the file. The time is specified as milliseconds
- /// from Jan 1, 1970 which is the same as that which is returned by the
- /// <tt>lastModified()</tt>, <tt>getLastModified()</tt>, and <tt>getDate()</tt> methods.
- /// <p/>
- /// This method does not apply to workgroups, servers, or shares.
- /// </remarks>
- /// <param name="time">the last modified time as milliseconds since Jan 1, 1970</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void SetLastModified(long time)
- {
- if (GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- SetPathInformation(0, 0L, time);
- }
-
- /// <summary>Return the attributes of this file.</summary>
- /// <remarks>
- /// Return the attributes of this file. Attributes are represented as a
- /// bitset that must be masked with <tt>ATTR_*</tt> constants to determine
- /// if they are set or unset. The value returned is suitable for use with
- /// the <tt>setAttributes()</tt> method.
- /// </remarks>
- /// <returns>the <tt>ATTR_*</tt> attributes associated with this file</returns>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual int GetAttributes()
- {
- if (GetUncPath0().Length == 1)
- {
- return 0;
- }
- Exists();
- return _attributes & AttrGetMask;
- }
-
- /// <summary>Set the attributes of this file.</summary>
- /// <remarks>
- /// Set the attributes of this file. Attributes are composed into a
- /// bitset by bitwise ORing the <tt>ATTR_*</tt> constants. Setting the
- /// value returned by <tt>getAttributes</tt> will result in both files
- /// having the same attributes.
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void SetAttributes(int attrs)
- {
- if (GetUncPath0().Length == 1)
- {
- throw new SmbException("Invalid operation for workgroups, servers, or shares");
- }
- SetPathInformation(attrs & AttrSetMask, 0L, 0L);
- }
-
- /// <summary>Make this file read-only.</summary>
- /// <remarks>
- /// Make this file read-only. This is shorthand for <tt>setAttributes(
- /// getAttributes() | ATTR_READ_ONLY )</tt>.
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void SetReadOnly()
- {
- SetAttributes(GetAttributes() | AttrReadonly);
- }
-
- /// <summary>Turn off the read-only attribute of this file.</summary>
- /// <remarks>
- /// Turn off the read-only attribute of this file. This is shorthand for
- /// <tt>setAttributes( getAttributes() & ~ATTR_READONLY )</tt>.
- /// </remarks>
- /// <exception cref="SmbException">SmbException</exception>
- /// <exception cref="SmbException"></exception>
- public virtual void SetReadWrite()
- {
- SetAttributes(GetAttributes() & ~AttrReadonly);
- }
-
- /// <summary>
- /// Returns a
- /// <see cref="System.Uri">System.Uri</see>
- /// for this <code>SmbFile</code>. The
- /// <code>URL</code> may be used as any other <code>URL</code> might to
- /// access an SMB resource. Currently only retrieving data and information
- /// is supported (i.e. no <tt>doOutput</tt>).
- /// </summary>
- /// <returns>
- /// A new <code>
- /// <see cref="System.Uri">System.Uri</see>
- /// </code> for this <code>SmbFile</code>
- /// </returns>
- /// <exception cref="System.UriFormatException">System.UriFormatException</exception>
- [Obsolete(@"Use getURL() instead")]
- public virtual Uri ToUrl()
- {
- return Url;
- }
-
- /// <summary>
- /// Computes a hashCode for this file based on the URL string and IP
- /// address if the server.
- /// </summary>
- /// <remarks>
- /// Computes a hashCode for this file based on the URL string and IP
- /// address if the server. The hashing function uses the hashcode of the
- /// server address, the canonical representation of the URL, and does not
- /// compare authentication information. In essance, two
- /// <code>SmbFile</code> objects that refer to
- /// the same file should generate the same hashcode provided it is possible
- /// to make such a determination.
- /// </remarks>
- /// <returns>A hashcode for this abstract file</returns>
- /// <exception cref="SmbException">SmbException</exception>
- public override int GetHashCode()
- {
- int hash;
- try
- {
- hash = GetAddress().GetHashCode();
- }
- catch (UnknownHostException)
- {
- hash = GetServer().ToUpper().GetHashCode();
- }
- GetUncPath0();
- return hash + _canon.ToUpper().GetHashCode();
- }
-
- protected internal virtual bool PathNamesPossiblyEqual(string path1, string path2
- )
- {
- int p1;
- int p2;
- int l1;
- int l2;
- // if unsure return this method returns true
- p1 = path1.LastIndexOf('/');
- p2 = path2.LastIndexOf('/');
- l1 = path1.Length - p1;
- l2 = path2.Length - p2;
- // anything with dots voids comparison
- if (l1 > 1 && path1[p1 + 1] == '.')
- {
- return true;
- }
- if (l2 > 1 && path2[p2 + 1] == '.')
- {
- return true;
- }
- return l1 == l2 && path1.RegionMatches(true, p1, path2, p2, l1);
- }
-
- /// <summary>Tests to see if two <code>SmbFile</code> objects are equal.</summary>
- /// <remarks>
- /// Tests to see if two <code>SmbFile</code> objects are equal. Two
- /// SmbFile objects are equal when they reference the same SMB
- /// resource. More specifically, two <code>SmbFile</code> objects are
- /// equals if their server IP addresses are equal and the canonicalized
- /// representation of their URLs, minus authentication parameters, are
- /// case insensitivly and lexographically equal.
- /// <p/>
- /// For example, assuming the server <code>angus</code> resolves to the
- /// <code>192.168.1.15</code> IP address, the below URLs would result in
- /// <code>SmbFile</code>s that are equal.
- /// <p><blockquote><pre>
- /// smb://192.168.1.15/share/DIR/foo.txt
- /// smb://angus/share/data/../dir/foo.txt
- /// </pre></blockquote>
- /// </remarks>
- /// <param name="obj">Another <code>SmbFile</code> object to compare for equality</param>
- /// <returns>
- /// <code>true</code> if the two objects refer to the same SMB resource
- /// and <code>false</code> otherwise
- /// </returns>
- /// <exception cref="SmbException">SmbException</exception>
- public override bool Equals(object obj)
- {
- if (obj is SmbFile)
- {
- SmbFile f = (SmbFile)obj;
- bool ret;
- if (this == f)
- {
- return true;
- }
- if (PathNamesPossiblyEqual(Url.AbsolutePath, f.Url.AbsolutePath))
- {
- GetUncPath0();
- f.GetUncPath0();
- if (Runtime.EqualsIgnoreCase(_canon, f._canon))
- {
- try
- {
- ret = GetAddress().Equals(f.GetAddress());
- }
- catch (UnknownHostException)
- {
- ret = Runtime.EqualsIgnoreCase(GetServer(), f.GetServer());
- }
- return ret;
- }
- }
- }
- return false;
- }
-
- /// <summary>Returns the string representation of this SmbFile object.</summary>
- /// <remarks>
- /// Returns the string representation of this SmbFile object. This will
- /// be the same as the URL used to construct this <code>SmbFile</code>.
- /// This method will return the same value
- /// as <code>getPath</code>.
- /// </remarks>
- /// <returns>The original URL representation of this SMB resource</returns>
- /// <exception cref="SmbException">SmbException</exception>
- public override string ToString()
- {
- return Url.ToString();
- }
-
- /// <summary>This URLConnection method just returns the result of <tt>length()</tt>.</summary>
- /// <remarks>This URLConnection method just returns the result of <tt>length()</tt>.</remarks>
- /// <returns>the length of this file or 0 if it refers to a directory</returns>
- public int GetContentLength()
- {
- try
- {
- return (int)(Length() & unchecked(0xFFFFFFFFL));
- }
- catch (SmbException)
- {
- }
- return 0;
- }
-
- /// <summary>This URLConnection method just returns the result of <tt>lastModified</tt>.
- /// </summary>
- /// <remarks>This URLConnection method just returns the result of <tt>lastModified</tt>.
- /// </remarks>
- /// <returns>the last modified data as milliseconds since Jan 1, 1970</returns>
- public long GetDate()
- {
- try
- {
- return LastModified();
- }
- catch (SmbException)
- {
- }
- return 0L;
- }
-
- /// <summary>This URLConnection method just returns the result of <tt>lastModified</tt>.
- /// </summary>
- /// <remarks>This URLConnection method just returns the result of <tt>lastModified</tt>.
- /// </remarks>
- /// <returns>the last modified data as milliseconds since Jan 1, 1970</returns>
- public long GetLastModified()
- {
- try
- {
- return LastModified();
- }
- catch (SmbException)
- {
- }
- return 0L;
- }
-
- /// <summary>This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file.
- /// </summary>
- /// <remarks>This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file.
- /// </remarks>
- /// <exception cref="System.IO.IOException">thrown by <tt>SmbFileInputStream</tt> constructor
- /// </exception>
- public InputStream GetInputStream()
- {
- return new SmbFileInputStream(this);
- }
-
- /// <summary>This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file.
- /// </summary>
- /// <remarks>This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file.
- /// </remarks>
- /// <exception cref="System.IO.IOException">thrown by <tt>SmbFileOutputStream</tt> constructor
- /// </exception>
- public OutputStream GetOutputStream()
- {
- return new SmbFileOutputStream(this);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- private void ProcessAces(Ace[] aces, bool resolveSids)
- {
- string server = GetServerWithDfs();
- int ai;
- if (resolveSids)
- {
- Sid[] sids = new Sid[aces.Length];
- string[] names = null;
- for (ai = 0; ai < aces.Length; ai++)
- {
- sids[ai] = aces[ai].Sid;
- }
- for (int off = 0; off < sids.Length; off += 64)
- {
- int len = sids.Length - off;
- if (len > 64)
- {
- len = 64;
- }
- Sid.ResolveSids(server, Auth, sids, off, len);
- }
- }
- else
- {
- for (ai = 0; ai < aces.Length; ai++)
- {
- aces[ai].Sid.OriginServer = server;
- aces[ai].Sid.OriginAuth = Auth;
- }
- }
- }
-
- /// <summary>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the security descriptor associated with this file or directory.
- /// </summary>
- /// <remarks>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the security descriptor associated with this file or directory.
- /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned.
- /// </remarks>
- /// <param name="resolveSids">
- /// Attempt to resolve the SIDs within each ACE form
- /// their numeric representation to their corresponding account names.
- /// </param>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual Ace[] GetSecurity(bool resolveSids)
- {
- int f;
- Ace[] aces;
- f = Open0(ORdonly, SmbConstants.ReadControl, 0, IsDirectory() ? 1 : 0);
- NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04);
- NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(
- );
- try
- {
- Send(request, response);
- }
- finally
- {
- Close(f, 0L);
- }
- aces = response.SecurityDescriptor.Aces;
- if (aces != null)
- {
- ProcessAces(aces, resolveSids);
- }
- return aces;
- }
-
- /// <summary>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the share permissions on the share exporting this file or directory.
- /// </summary>
- /// <remarks>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the share permissions on the share exporting this file or directory.
- /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned.
- /// <p>
- /// Note that this is different from calling <tt>getSecurity</tt> on a
- /// share. There are actually two different ACLs for shares - the ACL on
- /// the share and the ACL on the folder being shared.
- /// Go to <i>Computer Management</i>
- /// &gt; <i>System Tools</i> &gt; <i>Shared Folders</i> &gt <i>Shares</i> and
- /// look at the <i>Properties</i> for a share. You will see two tabs - one
- /// for "Share Permissions" and another for "Security". These correspond to
- /// the ACLs returned by <tt>getShareSecurity</tt> and <tt>getSecurity</tt>
- /// respectively.
- /// </remarks>
- /// <param name="resolveSids">
- /// Attempt to resolve the SIDs within each ACE form
- /// their numeric representation to their corresponding account names.
- /// </param>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual Ace[] GetShareSecurity(bool resolveSids)
- {
- string p = Url.AbsolutePath;
- MsrpcShareGetInfo rpc;
- DcerpcHandle handle;
- Ace[] aces;
- ResolveDfs(null);
- string server = GetServerWithDfs();
- rpc = new MsrpcShareGetInfo(server, Tree.Share);
- handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", Auth);
- try
- {
- handle.Sendrecv(rpc);
- if (rpc.Retval != 0)
- {
- throw new SmbException(rpc.Retval, true);
- }
- aces = rpc.GetSecurity();
- if (aces != null)
- {
- ProcessAces(aces, resolveSids);
- }
- }
- finally
- {
- try
- {
- handle.Close();
- }
- catch (IOException ioe)
- {
- if (Log.Level >= 1)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- }
- }
- return aces;
- }
-
- /// <summary>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the security descriptor associated with this file or directory.
- /// </summary>
- /// <remarks>
- /// Return an array of Access Control Entry (ACE) objects representing
- /// the security descriptor associated with this file or directory.
- /// <p>
- /// Initially, the SIDs within each ACE will not be resolved however when
- /// <tt>getType()</tt>, <tt>getDomainName()</tt>, <tt>getAccountName()</tt>,
- /// or <tt>toString()</tt> is called, the names will attempt to be
- /// resolved. If the names cannot be resolved (e.g. due to temporary
- /// network failure), the said methods will return default values (usually
- /// <tt>S-X-Y-Z</tt> strings of fragments of).
- /// <p>
- /// Alternatively <tt>getSecurity(true)</tt> may be used to resolve all
- /// SIDs together and detect network failures.
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual Ace[] GetSecurity()
- {
- return GetSecurity(false);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs
deleted file mode 100644
index 2ebcfa20f..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-// SmbFileExtensions.cs implementation by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using System;
-using System.Threading.Tasks;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- public static class SmbFileExtensions
- {
- /// <summary>
- /// Get file's creation date converted to local timezone
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static DateTime GetLocalCreateTime(this SmbFile smbFile)
- {
- return TimeZoneInfo.ConvertTime(Extensions.CreateDateFromUTC(smbFile.CreateTime()),
- TimeZoneInfo.Local);
- }
-
- /// <summary>
- /// Get file's last modified date converted to local timezone
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static DateTime GetLocalLastModified(this SmbFile smbFile)
- {
- return TimeZoneInfo.ConvertTime(Extensions.CreateDateFromUTC(smbFile.LastModified()),
- TimeZoneInfo.Local);
- }
-
-
- /// <summary>
- /// List files async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static Task<SmbFile[]> ListFilesAsync(this SmbFile smbFile)
- {
- return Task.Run(() => smbFile.ListFiles());
- }
-
- /// <summary>
- /// List files async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <param name="wildcard"></param>
- /// <returns></returns>
- public static Task<SmbFile[]> ListFilesAsync(this SmbFile smbFile, string wildcard)
- {
- return Task.Run(() => smbFile.ListFiles(wildcard));
- }
-
- /// <summary>
- /// List files async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static Task<string[]> ListAsync(this SmbFile smbFile)
- {
- return Task.Run(() => smbFile.List());
- }
-
- /// <summary>
- /// MkDir async method
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static Task MkDirAsync(this SmbFile smbFile)
- {
- return Task.Run(() => smbFile.Mkdir());
- }
-
-
- /// <summary>
- /// Delete file async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static Task DeleteAsync(this SmbFile smbFile)
- {
- return Task.Run(() => smbFile.Delete());
- }
-
- /// <summary>
- /// Rename file async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <param name="destination"></param>
- /// <returns></returns>
- public static Task RenameToAsync(this SmbFile smbFile, SmbFile destination)
- {
- return Task.Run(() => smbFile.RenameTo(destination));
- }
-
- /// <summary>
- /// Get input stream async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <returns></returns>
- public static Task<InputStream> GetInputStreamAsync(this SmbFile smbFile)
- {
- return Task.Run(() => smbFile.GetInputStream());
- }
-
-
- /// <summary>
- /// Get output stream async
- /// </summary>
- /// <param name="smbFile"></param>
- /// <param name="append"></param>
- /// <returns></returns>
- public static Task<OutputStream> GetOutputStreamAsync(this SmbFile smbFile, bool append = false)
- {
- return Task.Run(() => new SmbFileOutputStream(smbFile, append) as OutputStream);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs
deleted file mode 100644
index 196bfc1b6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public interface ISmbFileFilter
- {
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- bool Accept(SmbFile file);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs
deleted file mode 100644
index a9a0ea112..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs
+++ /dev/null
@@ -1,339 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util.Sharpen;
-using SharpCifs.Util.Transport;
-
-namespace SharpCifs.Smb
-{
- /// <summary>This InputStream can read bytes from a file on an SMB file server.</summary>
- /// <remarks>This InputStream can read bytes from a file on an SMB file server. Offsets are 64 bits.
- /// </remarks>
- public class SmbFileInputStream : InputStream
- {
- private long _fp;
-
- private int _readSize;
-
- private int _openFlags;
-
- private int _access;
-
- private byte[] _tmp = new byte[1];
-
- internal SmbFile File;
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.InputStream">System.IO.InputStream</see>
- /// for reading bytes from a file on
- /// an SMB server addressed by the <code>url</code> parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of the smb
- /// URL syntax.
- /// </summary>
- /// <param name="url">An smb URL string representing the file to read from</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileInputStream(string url) : this(new SmbFile(url))
- {
- }
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.InputStream">System.IO.InputStream</see>
- /// for reading bytes from a file on
- /// an SMB server represented by the
- /// <see cref="SmbFile">SmbFile</see>
- /// parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of
- /// the smb URL syntax.
- /// </summary>
- /// <param name="file">An <code>SmbFile</code> specifying the file to read from</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileInputStream(SmbFile file) : this(file, SmbFile.ORdonly)
- {
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- internal SmbFileInputStream(SmbFile file, int openFlags)
- {
- this.File = file;
- this._openFlags = openFlags & 0xFFFF;
- _access = ((int)(((uint)openFlags) >> 16)) & 0xFFFF;
- if (file.Type != SmbFile.TypeNamedPipe)
- {
- file.Open(openFlags, _access, SmbFile.AttrNormal, 0);
- this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc);
- }
- else
- {
- file.Connect0();
- }
- _readSize = Math.Min(file.Tree.Session.transport.RcvBufSize - 70, file.Tree.Session
- .transport.Server.MaxBufferSize - 70);
- }
-
- protected internal virtual IOException SeToIoe(SmbException se)
- {
- IOException ioe = se;
- Exception root = se.GetRootCause();
- if (root is TransportException)
- {
- ioe = (TransportException)root;
- root = ((TransportException)ioe).GetRootCause();
- }
- if (root is Exception)
- {
- ioe = new IOException(root.Message);
- ioe.InitCause(root);
- }
- return ioe;
- }
-
- /// <summary>Closes this input stream and releases any system resources associated with the stream.
- /// </summary>
- /// <remarks>Closes this input stream and releases any system resources associated with the stream.
- /// </remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override void Close()
- {
- try
- {
- File.Close();
- _tmp = null;
- }
- catch (SmbException se)
- {
- throw SeToIoe(se);
- }
- }
-
- /// <summary>Reads a byte of data from this input stream.</summary>
- /// <remarks>Reads a byte of data from this input stream.</remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override int Read()
- {
- // need oplocks to cache otherwise use BufferedInputStream
- if (Read(_tmp, 0, 1) == -1)
- {
- return -1;
- }
- return _tmp[0] & unchecked(0xFF);
- }
-
- /// <summary>Reads up to b.length bytes of data from this input stream into an array of bytes.
- /// </summary>
- /// <remarks>Reads up to b.length bytes of data from this input stream into an array of bytes.
- /// </remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override int Read(byte[] b)
- {
- return Read(b, 0, b.Length);
- }
-
- /// <summary>Reads up to len bytes of data from this input stream into an array of bytes.
- /// </summary>
- /// <remarks>Reads up to len bytes of data from this input stream into an array of bytes.
- /// </remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override int Read(byte[] b, int off, int len)
- {
- return ReadDirect(b, off, len);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual int ReadDirect(byte[] b, int off, int len)
- {
- if (len <= 0)
- {
- return 0;
- }
-
- long start = _fp;
- if (_tmp == null)
- {
- throw new IOException("Bad file descriptor");
- }
-
- // ensure file is open
- File.Open(_openFlags, _access, SmbFile.AttrNormal, 0);
- if (File.Log.Level >= 4)
- {
- File.Log.WriteLine("read: fid=" + File.Fid + ",off=" + off + ",len=" + len);
- }
-
- SmbComReadAndXResponse response = new SmbComReadAndXResponse(b, off);
- if (File.Type == SmbFile.TypeNamedPipe)
- {
- response.ResponseTimeout = 0;
- }
-
- int r;
- int n;
- do
- {
- r = len > _readSize ? _readSize : len;
- if (File.Log.Level >= 4)
- {
- File.Log.WriteLine("read: len=" + len + ",r=" + r + ",fp=" + _fp);
- }
-
- try
- {
- SmbComReadAndX request = new SmbComReadAndX(File.Fid, _fp, r, null);
- if (File.Type == SmbFile.TypeNamedPipe)
- {
- request.MinCount = request.MaxCount = request.Remaining = 1024;
- }
- //œǂݍł炵B
- File.Send(request, response);
- }
- catch (SmbException se)
- {
- if (File.Type == SmbFile.TypeNamedPipe && se.GetNtStatus() == NtStatus.NtStatusPipeBroken)
- {
- return -1;
- }
- throw SeToIoe(se);
- }
-
- if ((n = response.DataLength) <= 0)
- {
- return (int)((_fp - start) > 0L ? _fp - start : -1);
- }
-
- _fp += n;
- len -= n;
- response.Off += n;
- }
- while (len > 0 && n == r);
-
-
- return (int)(_fp - start);
- }
-
- /// <summary>This stream class is unbuffered.</summary>
- /// <remarks>
- /// This stream class is unbuffered. Therefore this method will always
- /// return 0 for streams connected to regular files. However, a
- /// stream created from a Named Pipe this method will query the server using a
- /// "peek named pipe" operation and return the number of available bytes
- /// on the server.
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public override int Available()
- {
- SmbNamedPipe pipe;
- TransPeekNamedPipe req;
- TransPeekNamedPipeResponse resp;
- if (File.Type != SmbFile.TypeNamedPipe)
- {
- return 0;
- }
- try
- {
- pipe = (SmbNamedPipe)File;
- File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal
- , 0);
- req = new TransPeekNamedPipe(File.Unc, File.Fid);
- resp = new TransPeekNamedPipeResponse(pipe);
- pipe.Send(req, resp);
- if (resp.status == TransPeekNamedPipeResponse.StatusDisconnected || resp.status
- == TransPeekNamedPipeResponse.StatusServerEndClosed)
- {
- File.Opened = false;
- return 0;
- }
- return resp.Available;
- }
- catch (SmbException se)
- {
- throw SeToIoe(se);
- }
- }
-
- /// <summary>Skip n bytes of data on this stream.</summary>
- /// <remarks>
- /// Skip n bytes of data on this stream. This operation will not result
- /// in any IO with the server. Unlink <tt>InputStream</tt> value less than
- /// the one provided will not be returned if it exceeds the end of the file
- /// (if this is a problem let us know).
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public override long Skip(long n)
- {
- if (n > 0)
- {
- _fp += n;
- return n;
- }
- return 0;
- }
-
-
- /// <summary>
- /// Position in Stream
- /// </summary>
- /// <remarks>
- /// Add by dobes
- /// mod interface to WrappedSystemStream readable, for random access.
- /// </remarks>
- internal override long Position {
- get { return this._fp; }
- set
- {
- var tmpPos = value;
- var length = File.Length();
- if (tmpPos < 0)
- tmpPos = 0;
- else if (length < tmpPos)
- tmpPos = length;
- this._fp = tmpPos;
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- /// <remarks>
- /// Add by dobes
- /// mod interface to WrappedSystemStream readable, for random access.
- /// </remarks>
- internal override bool CanSeek()
- {
- return (File.Length() >= 0);
- }
-
- /// <summary>
- /// Get file length
- /// </summary>
- public override long Length
- {
- get { return File.Length(); }
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs
deleted file mode 100644
index 58c704dd7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs
+++ /dev/null
@@ -1,335 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>This <code>OutputStream</code> can write bytes to a file on an SMB file server.
- /// </summary>
- /// <remarks>This <code>OutputStream</code> can write bytes to a file on an SMB file server.
- /// </remarks>
- public class SmbFileOutputStream : OutputStream
- {
- private SmbFile _file;
-
- private bool _append;
-
- private bool _useNtSmbs;
-
- private int _openFlags;
-
- private int _access;
-
- private int _writeSize;
-
- private long _fp;
-
- private byte[] _tmp = new byte[1];
-
- private SmbComWriteAndX _reqx;
-
- private SmbComWriteAndXResponse _rspx;
-
- private SmbComWrite _req;
-
- private SmbComWriteResponse _rsp;
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.OutputStream">System.IO.OutputStream</see>
- /// for writing to a file
- /// on an SMB server addressed by the URL parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of
- /// the smb URL syntax.
- /// </summary>
- /// <param name="url">An smb URL string representing the file to write to</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileOutputStream(string url) : this(url, false)
- {
- }
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.OutputStream">System.IO.OutputStream</see>
- /// for writing bytes to a file on
- /// an SMB server represented by the
- /// <see cref="SmbFile">SmbFile</see>
- /// parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of
- /// the smb URL syntax.
- /// </summary>
- /// <param name="file">An <code>SmbFile</code> specifying the file to write to</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileOutputStream(SmbFile file) : this(file, false)
- {
- }
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.OutputStream">System.IO.OutputStream</see>
- /// for writing bytes to a file on an
- /// SMB server addressed by the URL parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of the smb URL syntax. If the
- /// second argument is <code>true</code>, then bytes will be written to the
- /// end of the file rather than the beginning.
- /// </summary>
- /// <param name="url">An smb URL string representing the file to write to</param>
- /// <param name="append">Append to the end of file</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileOutputStream(string url, bool append) : this(new SmbFile(url), append
- )
- {
- }
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.OutputStream">System.IO.OutputStream</see>
- /// for writing bytes to a file
- /// on an SMB server addressed by the <code>SmbFile</code> parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of
- /// the smb URL syntax. If the second argument is <code>true</code>, then
- /// bytes will be written to the end of the file rather than the beginning.
- /// </summary>
- /// <param name="file">An <code>SmbFile</code> representing the file to write to</param>
- /// <param name="append">Append to the end of file</param>
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileOutputStream(SmbFile file, bool append) : this(file, append, append
- ? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend : SmbFile.OCreat | SmbFile
- .OWronly | SmbFile.OTrunc)
- {
- }
-
- /// <summary>
- /// Creates an
- /// <see cref="System.IO.OutputStream">System.IO.OutputStream</see>
- /// for writing bytes to a file
- /// on an SMB server addressed by the <code>SmbFile</code> parameter. See
- /// <see cref="SmbFile">SmbFile</see>
- /// for a detailed description and examples of
- /// the smb URL syntax.
- /// <p>
- /// The second parameter specifies how the file should be shared. If
- /// <code>SmbFile.FILE_NO_SHARE</code> is specified the client will
- /// have exclusive access to the file. An additional open command
- /// from jCIFS or another application will fail with the "file is being
- /// accessed by another process" error. The <code>FILE_SHARE_READ</code>,
- /// <code>FILE_SHARE_WRITE</code>, and <code>FILE_SHARE_DELETE</code> may be
- /// combined with the bitwise OR '|' to specify that other peocesses may read,
- /// write, and/or delete the file while the jCIFS user has the file open.
- /// </summary>
- /// <param name="url">An smb URL representing the file to write to</param>
- /// <param name="shareAccess">File sharing flag: <code>SmbFile.FILE_NOSHARE</code> or any combination of <code>SmbFile.FILE_READ</code>, <code>SmbFile.FILE_WRITE</code>, and <code>SmbFile.FILE_DELETE</code>
- /// </param>
- /// <exception cref="Jcifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbFileOutputStream(string url, int shareAccess) : this(new SmbFile(url, string.Empty
- , null, shareAccess), false)
- {
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- internal SmbFileOutputStream(SmbFile file, bool append, int openFlags)
- {
- this._file = file;
- this._append = append;
- this._openFlags = openFlags;
- _access = ((int)(((uint)openFlags) >> 16)) & 0xFFFF;
- if (append)
- {
- try
- {
- _fp = file.Length();
- }
- catch (SmbAuthException sae)
- {
- throw;
- }
- catch (SmbException)
- {
- _fp = 0L;
- }
- }
- if (file is SmbNamedPipe && file.Unc.StartsWith("\\pipe\\"))
- {
- file.Unc = Runtime.Substring(file.Unc, 5);
- file.Send(new TransWaitNamedPipe("\\pipe" + file.Unc), new TransWaitNamedPipeResponse
- ());
- }
- file.Open(openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal,
- 0);
- this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc);
- _writeSize = file.Tree.Session.transport.SndBufSize - 70;
- _useNtSmbs = file.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs
- );
- if (_useNtSmbs)
- {
- _reqx = new SmbComWriteAndX();
- _rspx = new SmbComWriteAndXResponse();
- }
- else
- {
- _req = new SmbComWrite();
- _rsp = new SmbComWriteResponse();
- }
- }
-
- /// <summary>
- /// Closes this output stream and releases any system resources associated
- /// with it.
- /// </summary>
- /// <remarks>
- /// Closes this output stream and releases any system resources associated
- /// with it.
- /// </remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override void Close()
- {
- _file.Close();
- _tmp = null;
- }
-
- /// <summary>Writes the specified byte to this file output stream.</summary>
- /// <remarks>Writes the specified byte to this file output stream.</remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override void Write(int b)
- {
- _tmp[0] = unchecked((byte)b);
- Write(_tmp, 0, 1);
- }
-
- /// <summary>
- /// Writes b.length bytes from the specified byte array to this
- /// file output stream.
- /// </summary>
- /// <remarks>
- /// Writes b.length bytes from the specified byte array to this
- /// file output stream.
- /// </remarks>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override void Write(byte[] b)
- {
- Write(b, 0, b.Length);
- }
-
- public virtual bool IsOpen()
- {
- return _file.IsOpen();
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual void EnsureOpen()
- {
- // ensure file is open
- if (_file.IsOpen() == false)
- {
- _file.Open(_openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal,
- 0);
- if (_append)
- {
- _fp = _file.Length();
- }
- }
- }
-
- /// <summary>
- /// Writes len bytes from the specified byte array starting at
- /// offset off to this file output stream.
- /// </summary>
- /// <remarks>
- /// Writes len bytes from the specified byte array starting at
- /// offset off to this file output stream.
- /// </remarks>
- /// <param name="b">The array</param>
- /// <exception cref="System.IO.IOException">if a network error occurs</exception>
- public override void Write(byte[] b, int off, int len)
- {
- if (_file.IsOpen() == false && _file is SmbNamedPipe)
- {
- _file.Send(new TransWaitNamedPipe("\\pipe" + _file.Unc), new TransWaitNamedPipeResponse
- ());
- }
- WriteDirect(b, off, len, 0);
- }
-
- /// <summary>Just bypasses TransWaitNamedPipe - used by DCERPC bind.</summary>
- /// <remarks>Just bypasses TransWaitNamedPipe - used by DCERPC bind.</remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void WriteDirect(byte[] b, int off, int len, int flags)
- {
- if (len <= 0)
- {
- return;
- }
- if (_tmp == null)
- {
- throw new IOException("Bad file descriptor");
- }
- EnsureOpen();
- /*if (file.log.level >= 4)
- {
- file.log.WriteLine("write: fid=" + file.fid + ",off=" + off + ",len=" + len);
- }*/
- int w;
- do
- {
- w = len > _writeSize ? _writeSize : len;
- if (_useNtSmbs)
- {
- _reqx.SetParam(_file.Fid, _fp, len - w, b, off, w);
- if ((flags & 1) != 0)
- {
- _reqx.SetParam(_file.Fid, _fp, len, b, off, w);
- _reqx.WriteMode = 0x8;
- }
- else
- {
- _reqx.WriteMode = 0;
- }
- _file.Send(_reqx, _rspx);
- _fp += _rspx.Count;
- len -= (int)_rspx.Count;
- off += (int)_rspx.Count;
- }
- else
- {
- _req.SetParam(_file.Fid, _fp, len - w, b, off, w);
- _fp += _rsp.Count;
- len -= (int)_rsp.Count;
- off += (int)_rsp.Count;
- _file.Send(_req, _rsp);
- }
- }
- while (len > 0);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs
deleted file mode 100644
index b66dc133a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public interface ISmbFilenameFilter
- {
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- bool Accept(SmbFile dir, string name);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs
deleted file mode 100644
index f09e16cca..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs
+++ /dev/null
@@ -1,210 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- /// <summary>
- /// This class will allow a Java program to read and write data to Named
- /// Pipes and Transact NamedPipes.
- /// </summary>
- /// <remarks>
- /// This class will allow a Java program to read and write data to Named
- /// Pipes and Transact NamedPipes.
- /// <p>There are three Win32 function calls provided by the Windows SDK
- /// that are important in the context of using jCIFS. They are:
- /// <ul>
- /// <li> <code>CallNamedPipe</code> A message-type pipe call that opens,
- /// writes to, reads from, and closes the pipe in a single operation.
- /// <li> <code>TransactNamedPipe</code> A message-type pipe call that
- /// writes to and reads from an existing pipe descriptor in one operation.
- /// <li> <code>CreateFile</code>, <code>ReadFile</code>,
- /// <code>WriteFile</code>, and <code>CloseFile</code> A byte-type pipe can
- /// be opened, written to, read from and closed using the standard Win32
- /// file operations.
- /// </ul>
- /// <p>The jCIFS API maps all of these operations into the standard Java
- /// <code>XxxputStream</code> interface. A special <code>PIPE_TYPE</code>
- /// flags is necessary to distinguish which type of Named Pipe behavior
- /// is desired.
- /// <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
- /// <tr bgcolor="#ccccff">
- /// <td colspan="2"><b><code>SmbNamedPipe</code> Constructor Examples</b></td>
- /// <tr><td width="20%"><b>Code Sample</b></td><td><b>Description</b></td></tr>
- /// <tr><td width="20%"><pre>
- /// new SmbNamedPipe( "smb://server/IPC$/PIPE/foo",
- /// SmbNamedPipe.PIPE_TYPE_RDWR |
- /// SmbNamedPipe.PIPE_TYPE_CALL );
- /// </pre></td><td>
- /// Open the Named Pipe foo for reading and writing. The pipe will behave like the <code>CallNamedPipe</code> interface.
- /// </td></tr>
- /// <tr><td width="20%"><pre>
- /// new SmbNamedPipe( "smb://server/IPC$/foo",
- /// SmbNamedPipe.PIPE_TYPE_RDWR |
- /// SmbNamedPipe.PIPE_TYPE_TRANSACT );
- /// </pre></td><td>
- /// Open the Named Pipe foo for reading and writing. The pipe will behave like the <code>TransactNamedPipe</code> interface.
- /// </td></tr>
- /// <tr><td width="20%"><pre>
- /// new SmbNamedPipe( "smb://server/IPC$/foo",
- /// SmbNamedPipe.PIPE_TYPE_RDWR );
- /// </pre></td><td>
- /// Open the Named Pipe foo for reading and writing. The pipe will
- /// behave as though the <code>CreateFile</code>, <code>ReadFile</code>,
- /// <code>WriteFile</code>, and <code>CloseFile</code> interface was
- /// being used.
- /// </td></tr>
- /// </table>
- /// <p>See <a href="../../../pipes.html">Using jCIFS to Connect to Win32
- /// Named Pipes</a> for a detailed description of how to use jCIFS with
- /// Win32 Named Pipe server processes.
- /// </remarks>
- public class SmbNamedPipe : SmbFile
- {
- /// <summary>The pipe should be opened read-only.</summary>
- /// <remarks>The pipe should be opened read-only.</remarks>
- public const int PipeTypeRdonly = ORdonly;
-
- /// <summary>The pipe should be opened only for writing.</summary>
- /// <remarks>The pipe should be opened only for writing.</remarks>
- public const int PipeTypeWronly = OWronly;
-
- /// <summary>The pipe should be opened for both reading and writing.</summary>
- /// <remarks>The pipe should be opened for both reading and writing.</remarks>
- public const int PipeTypeRdwr = ORdwr;
-
- /// <summary>Pipe operations should behave like the <code>CallNamedPipe</code> Win32 Named Pipe function.
- /// </summary>
- /// <remarks>Pipe operations should behave like the <code>CallNamedPipe</code> Win32 Named Pipe function.
- /// </remarks>
- public const int PipeTypeCall = unchecked(0x0100);
-
- /// <summary>Pipe operations should behave like the <code>TransactNamedPipe</code> Win32 Named Pipe function.
- /// </summary>
- /// <remarks>Pipe operations should behave like the <code>TransactNamedPipe</code> Win32 Named Pipe function.
- /// </remarks>
- public const int PipeTypeTransact = unchecked(0x0200);
-
- public const int PipeTypeDceTransact = unchecked(0x0200) | unchecked(0x0400);
-
- internal InputStream PipeIn;
-
- internal OutputStream PipeOut;
-
- internal int PipeType;
-
- /// <summary>
- /// Open the Named Pipe resource specified by the url
- /// parameter.
- /// </summary>
- /// <remarks>
- /// Open the Named Pipe resource specified by the url
- /// parameter. The pipeType parameter should be at least one of
- /// the <code>PIPE_TYPE</code> flags combined with the bitwise OR
- /// operator <code>|</code>. See the examples listed above.
- /// </remarks>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbNamedPipe(string url, int pipeType) : base(url)
- {
- this.PipeType = pipeType;
- Type = TypeNamedPipe;
- }
-
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbNamedPipe(string url, int pipeType, NtlmPasswordAuthentication auth) :
- base(url, auth)
- {
- this.PipeType = pipeType;
- Type = TypeNamedPipe;
- }
-
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth) : base
- (url, auth)
- {
- this.PipeType = pipeType;
- Type = TypeNamedPipe;
- }
-
- /// <summary>
- /// Return the <code>InputStream</code> used to read information
- /// from this pipe instance.
- /// </summary>
- /// <remarks>
- /// Return the <code>InputStream</code> used to read information
- /// from this pipe instance. Presumably data would first be written
- /// to the <code>OutputStream</code> associated with this Named
- /// Pipe instance although this is not a requirement (e.g. a
- /// read-only named pipe would write data to this stream on
- /// connection). Reading from this stream may block. Therefore it
- /// may be necessary that an addition thread be used to read and
- /// write to a Named Pipe.
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual InputStream GetNamedPipeInputStream()
- {
- if (PipeIn == null)
- {
- if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact
- ) == PipeTypeTransact)
- {
- PipeIn = new TransactNamedPipeInputStream(this);
- }
- else
- {
- PipeIn = new SmbFileInputStream(this, (PipeType & unchecked((int)(0xFFFF00FF))) |
- OExcl);
- }
- }
- return PipeIn;
- }
-
- /// <summary>
- /// Return the <code>OutputStream</code> used to write
- /// information to this pipe instance.
- /// </summary>
- /// <remarks>
- /// Return the <code>OutputStream</code> used to write
- /// information to this pipe instance. The act of writing data
- /// to this stream will result in response data recieved in the
- /// <code>InputStream</code> associated with this Named Pipe
- /// instance (unless of course it does not elicite a response or the pipe is write-only).
- /// </remarks>
- /// <exception cref="System.IO.IOException"></exception>
- public virtual OutputStream GetNamedPipeOutputStream()
- {
- if (PipeOut == null)
- {
- if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact
- ) == PipeTypeTransact)
- {
- PipeOut = new TransactNamedPipeOutputStream(this);
- }
- else
- {
- PipeOut = new SmbFileOutputStream(this, false, (PipeType & unchecked((int)(0xFFFF00FF
- ))) | OExcl);
- }
- }
- return PipeOut;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs
deleted file mode 100644
index 445a0656c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs
+++ /dev/null
@@ -1,506 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using System.Text;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- public class SmbRandomAccessFile //: DataOutput, DataInput
- {
- private const int WriteOptions = unchecked(0x0842);
-
- private SmbFile _file;
-
- private long _fp;
-
- private int _openFlags;
-
- private int _access;
-
- private int _readSize;
-
- private int _writeSize;
-
- private int _ch;
-
- private int _options;
-
- private byte[] _tmp = new byte[8];
-
- private SmbComWriteAndXResponse _writeAndxResp;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbRandomAccessFile(string url, string mode, int shareAccess) : this(new SmbFile
- (url, string.Empty, null, shareAccess), mode)
- {
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public SmbRandomAccessFile(SmbFile file, string mode)
- {
- this._file = file;
- if (mode.Equals("r"))
- {
- _openFlags = SmbFile.OCreat | SmbFile.ORdonly;
- }
- else
- {
- if (mode.Equals("rw"))
- {
- _openFlags = SmbFile.OCreat | SmbFile.ORdwr | SmbFile.OAppend;
- _writeAndxResp = new SmbComWriteAndXResponse();
- _options = WriteOptions;
- _access = SmbConstants.FileReadData | SmbConstants.FileWriteData;
- }
- else
- {
- throw new ArgumentException("Invalid mode");
- }
- }
- file.Open(_openFlags, _access, SmbFile.AttrNormal, _options);
- _readSize = file.Tree.Session.transport.RcvBufSize - 70;
- _writeSize = file.Tree.Session.transport.SndBufSize - 70;
- _fp = 0L;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual int Read()
- {
- if (Read(_tmp, 0, 1) == -1)
- {
- return -1;
- }
- return _tmp[0] & unchecked(0xFF);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual int Read(byte[] b)
- {
- return Read(b, 0, b.Length);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual int Read(byte[] b, int off, int len)
- {
- if (len <= 0)
- {
- return 0;
- }
- long start = _fp;
- // ensure file is open
- if (_file.IsOpen() == false)
- {
- _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options);
- }
- int r;
- int n;
- SmbComReadAndXResponse response = new SmbComReadAndXResponse(b, off);
- do
- {
- r = len > _readSize ? _readSize : len;
- _file.Send(new SmbComReadAndX(_file.Fid, _fp, r, null), response);
- if ((n = response.DataLength) <= 0)
- {
- return (int)((_fp - start) > 0L ? _fp - start : -1);
- }
- _fp += n;
- len -= n;
- response.Off += n;
- }
- while (len > 0 && n == r);
- return (int)(_fp - start);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void ReadFully(byte[] b)
- {
- ReadFully(b, 0, b.Length);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void ReadFully(byte[] b, int off, int len)
- {
- int n = 0;
- int count;
- do
- {
- count = Read(b, off + n, len - n);
- if (count < 0)
- {
- throw new SmbException("EOF");
- }
- n += count;
- _fp += count;
- }
- while (n < len);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual int SkipBytes(int n)
- {
- if (n > 0)
- {
- _fp += n;
- return n;
- }
- return 0;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Write(int b)
- {
- _tmp[0] = unchecked((byte)b);
- Write(_tmp, 0, 1);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Write(byte[] b)
- {
- Write(b, 0, b.Length);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Write(byte[] b, int off, int len)
- {
- if (len <= 0)
- {
- return;
- }
- // ensure file is open
- if (_file.IsOpen() == false)
- {
- _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options);
- }
- int w;
- do
- {
- w = len > _writeSize ? _writeSize : len;
- _file.Send(new SmbComWriteAndX(_file.Fid, _fp, len - w, b, off, w, null), _writeAndxResp
- );
- _fp += _writeAndxResp.Count;
- len -= (int)_writeAndxResp.Count;
- off += (int)_writeAndxResp.Count;
- }
- while (len > 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long GetFilePointer()
- {
- return _fp;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Seek(long pos)
- {
- _fp = pos;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual long Length()
- {
- return _file.Length();
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void SetLength(long newLength)
- {
- // ensure file is open
- if (_file.IsOpen() == false)
- {
- _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options);
- }
- SmbComWriteResponse rsp = new SmbComWriteResponse();
- _file.Send(new SmbComWrite(_file.Fid, (int)(newLength & unchecked(0xFFFFFFFFL)), 0, _tmp, 0, 0), rsp);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Close()
- {
- _file.Close();
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public bool ReadBoolean()
- {
- if ((Read(_tmp, 0, 1)) < 0)
- {
- throw new SmbException("EOF");
- }
- return _tmp[0] != unchecked(unchecked(0x00));
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public byte ReadByte()
- {
- if ((Read(_tmp, 0, 1)) < 0)
- {
- throw new SmbException("EOF");
- }
- return _tmp[0];
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public int ReadUnsignedByte()
- {
- if ((Read(_tmp, 0, 1)) < 0)
- {
- throw new SmbException("EOF");
- }
- return _tmp[0] & unchecked(0xFF);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public short ReadShort()
- {
- if ((Read(_tmp, 0, 2)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_uint16be(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public int ReadUnsignedShort()
- {
- if ((Read(_tmp, 0, 2)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_uint16be(_tmp, 0) & unchecked(0xFFFF);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public char ReadChar()
- {
- if ((Read(_tmp, 0, 2)) < 0)
- {
- throw new SmbException("EOF");
- }
- return (char)Encdec.Dec_uint16be(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public int ReadInt()
- {
- if ((Read(_tmp, 0, 4)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_uint32be(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public long ReadLong()
- {
- if ((Read(_tmp, 0, 8)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_uint64be(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public float ReadFloat()
- {
- if ((Read(_tmp, 0, 4)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_floatbe(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public double ReadDouble()
- {
- if ((Read(_tmp, 0, 8)) < 0)
- {
- throw new SmbException("EOF");
- }
- return Encdec.Dec_doublebe(_tmp, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public string ReadLine()
- {
- StringBuilder input = new StringBuilder();
- int c = -1;
- bool eol = false;
- while (!eol)
- {
- switch (c = Read())
- {
- case -1:
- case '\n':
- {
- eol = true;
- break;
- }
-
- case '\r':
- {
- eol = true;
- long cur = _fp;
- if (Read() != '\n')
- {
- _fp = cur;
- }
- break;
- }
-
- default:
- {
- input.Append((char)c);
- break;
- }
- }
- }
- if ((c == -1) && (input.Length == 0))
- {
- return null;
- }
- return input.ToString();
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public string ReadUtf()
- {
- int size = ReadUnsignedShort();
- byte[] b = new byte[size];
- Read(b, 0, size);
- try
- {
- return Encdec.Dec_utf8(b, 0, size);
- }
- catch (IOException ioe)
- {
- throw new SmbException(string.Empty, ioe);
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteBoolean(bool v)
- {
- _tmp[0] = unchecked((byte)(v ? 1 : 0));
- Write(_tmp, 0, 1);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteByte(int v)
- {
- _tmp[0] = unchecked((byte)v);
- Write(_tmp, 0, 1);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteShort(int v)
- {
- Encdec.Enc_uint16be((short)v, _tmp, 0);
- Write(_tmp, 0, 2);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteChar(int v)
- {
- Encdec.Enc_uint16be((short)v, _tmp, 0);
- Write(_tmp, 0, 2);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteInt(int v)
- {
- Encdec.Enc_uint32be(v, _tmp, 0);
- Write(_tmp, 0, 4);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteLong(long v)
- {
- Encdec.Enc_uint64be(v, _tmp, 0);
- Write(_tmp, 0, 8);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteFloat(float v)
- {
- Encdec.Enc_floatbe(v, _tmp, 0);
- Write(_tmp, 0, 4);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteDouble(double v)
- {
- Encdec.Enc_doublebe(v, _tmp, 0);
- Write(_tmp, 0, 8);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteBytes(string s)
- {
- byte[] b = Runtime.GetBytesForString(s);
- Write(b, 0, b.Length);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /* public void WriteChars(string s)
- {
- int clen = s.Length;
- int blen = 2 * clen;
- byte[] b = new byte[blen];
- char[] c = new char[clen];
- Sharpen.Runtime.GetCharsForString(s, 0, clen, c, 0);
- for (int i = 0, j = 0; i < clen; i++)
- {
- b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 8)));
- b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 0)));
- }
- Write(b, 0, blen);
- }*/
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public void WriteUtf(string str)
- {
- int len = str.Length;
- int ch;
- int size = 0;
- byte[] dst;
- for (int i = 0; i < len; i++)
- {
- ch = str[i];
- size += ch > unchecked(0x07F) ? (ch > unchecked(0x7FF) ? 3 : 2) : 1;
- }
- dst = new byte[size];
- WriteShort(size);
- try
- {
- Encdec.Enc_utf8(str, dst, 0, size);
- }
- catch (IOException ioe)
- {
- throw new SmbException(string.Empty, ioe);
- }
- Write(dst, 0, size);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs
deleted file mode 100644
index 6dc5087d0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs
+++ /dev/null
@@ -1,570 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using SharpCifs.Netbios;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- public sealed class SmbSession
- {
- private static readonly string LogonShare = Config.GetProperty("jcifs.smb.client.logonShare"
- , null);
-
- private static readonly int LookupRespLimit = Config.GetInt("jcifs.netbios.lookupRespLimit"
- , 3);
-
- private static readonly string Domain = Config.GetProperty("jcifs.smb.client.domain"
- , null);
-
- private static readonly string Username = Config.GetProperty("jcifs.smb.client.username"
- , null);
-
- private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
- , 60 * 10) * 60;
-
- internal static NbtAddress[] DcList;
-
- internal static long DcListExpiration;
-
- internal static int DcListCounter;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- private static NtlmChallenge Interrogate(NbtAddress addr)
- {
- UniAddress dc = new UniAddress(addr);
- SmbTransport trans = SmbTransport.GetSmbTransport(dc, 0);
- if (Username == null)
- {
- trans.Connect();
- if (SmbTransport.LogStatic.Level >= 3)
- {
- SmbTransport.LogStatic.WriteLine("Default credentials (jcifs.smb.client.username/password)"
- + " not specified. SMB signing may not work propertly." + " Skipping DC interrogation."
- );
- }
- }
- else
- {
- SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default
- );
- ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null);
- }
- return new NtlmChallenge(trans.Server.EncryptionKey, dc);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public static NtlmChallenge GetChallengeForDomain()
- {
- if (Domain == null)
- {
- throw new SmbException("A domain was not specified");
- }
- lock (Domain)
- {
- long now = Runtime.CurrentTimeMillis();
- int retry = 1;
- do
- {
- if (DcListExpiration < now)
- {
- NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null,
- null);
- DcListExpiration = now + CachePolicy * 1000L;
- if (list != null && list.Length > 0)
- {
- DcList = list;
- }
- else
- {
- DcListExpiration = now + 1000 * 60 * 15;
- if (SmbTransport.LogStatic.Level >= 2)
- {
- SmbTransport.LogStatic.WriteLine("Failed to retrieve DC list from WINS");
- }
- }
- }
- int max = Math.Min(DcList.Length, LookupRespLimit);
- for (int j = 0; j < max; j++)
- {
- int i = DcListCounter++ % max;
- if (DcList[i] != null)
- {
- try
- {
- return Interrogate(DcList[i]);
- }
- catch (SmbException se)
- {
- if (SmbTransport.LogStatic.Level >= 2)
- {
- SmbTransport.LogStatic.WriteLine("Failed validate DC: " + DcList[i]);
- if (SmbTransport.LogStatic.Level > 2)
- {
- Runtime.PrintStackTrace(se, SmbTransport.LogStatic);
- }
- }
- }
- DcList[i] = null;
- }
- }
- DcListExpiration = 0;
- }
- while (retry-- > 0);
- DcListExpiration = now + 1000 * 60 * 15;
- }
- throw new UnknownHostException("Failed to negotiate with a suitable domain controller for "
- + Domain);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public static byte[] GetChallenge(UniAddress dc)
- {
- return GetChallenge(dc, 0);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- public static byte[] GetChallenge(UniAddress dc, int port)
- {
- SmbTransport trans = SmbTransport.GetSmbTransport(dc, port);
- trans.Connect();
- return trans.Server.EncryptionKey;
- }
-
- /// <summary>
- /// Authenticate arbitrary credentials represented by the
- /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
- /// specified by the <tt>UniAddress</tt> parameter.
- /// </summary>
- /// <remarks>
- /// Authenticate arbitrary credentials represented by the
- /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
- /// specified by the <tt>UniAddress</tt> parameter. If the credentials are
- /// not accepted, an <tt>SmbAuthException</tt> will be thrown. If an error
- /// occurs an <tt>SmbException</tt> will be thrown. If the credentials are
- /// valid, the method will return without throwing an exception. See the
- /// last <a href="../../../faq.html">FAQ</a> question.
- /// <p>
- /// See also the <tt>jcifs.smb.client.logonShare</tt> property.
- /// </remarks>
- /// <exception cref="SmbException"></exception>
- public static void Logon(UniAddress dc, NtlmPasswordAuthentication auth)
- {
- Logon(dc, -1, auth);
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth
- )
- {
- SmbTree tree = SmbTransport.GetSmbTransport(dc, port).GetSmbSession(auth).GetSmbTree
- (LogonShare, null);
- if (LogonShare == null)
- {
- tree.TreeConnect(null, null);
- }
- else
- {
- Trans2FindFirst2 req = new Trans2FindFirst2("\\", "*", SmbFile.AttrDirectory);
- Trans2FindFirst2Response resp = new Trans2FindFirst2Response();
- tree.Send(req, resp);
- }
- }
-
- internal int ConnectionState;
-
- internal int Uid;
-
- internal List<object> Trees;
-
- private UniAddress _address;
-
- private int _port;
-
- private int _localPort;
-
- private IPAddress _localAddr;
-
- internal SmbTransport transport;
-
- internal NtlmPasswordAuthentication Auth;
-
- internal long Expiration;
-
- internal string NetbiosName;
-
- internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort
- , NtlmPasswordAuthentication auth)
- {
- // Transport parameters allows trans to be removed from CONNECTIONS
- this._address = address;
- this._port = port;
- this._localAddr = localAddr;
- this._localPort = localPort;
- this.Auth = auth;
- Trees = new List<object>();
- ConnectionState = 0;
- }
-
- internal SmbTree GetSmbTree(string share, string service)
- {
- lock (this)
- {
- SmbTree t;
- if (share == null)
- {
- share = "IPC$";
- }
- /*for (IEnumeration e = trees.GetEnumerator(); e.MoveNext(); )
- {
- t = (SmbTree)e.Current;
- if (t.Matches(share, service))
- {
- return t;
- }
- }*/
- foreach (var e in Trees)
- {
- t = (SmbTree)e;
- if (t.Matches(share, service))
- {
- return t;
- }
- }
-
- t = new SmbTree(this, share, service);
- Trees.Add(t);
- return t;
- }
- }
-
- internal bool Matches(NtlmPasswordAuthentication auth)
- {
- return this.Auth == auth || this.Auth.Equals(auth);
- }
-
- internal SmbTransport Transport()
- {
- lock (this)
- {
- if (transport == null)
- {
- transport = SmbTransport.GetSmbTransport(_address, _port, _localAddr, _localPort, null
- );
- }
- return transport;
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal void Send(ServerMessageBlock request, ServerMessageBlock response)
- {
- lock (Transport())
- {
- if (response != null)
- {
- response.Received = false;
- }
- Expiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout;
- SessionSetup(request, response);
- if (response != null && response.Received)
- {
- return;
- }
- if (request is SmbComTreeConnectAndX)
- {
- SmbComTreeConnectAndX tcax = (SmbComTreeConnectAndX)request;
- if (NetbiosName != null && tcax.path.EndsWith("\\IPC$"))
- {
- tcax.path = "\\\\" + NetbiosName + "\\IPC$";
- }
- }
- request.Uid = Uid;
- request.Auth = Auth;
- try
- {
- transport.Send(request, response);
- }
- catch (SmbException se)
- {
- if (request is SmbComTreeConnectAndX)
- {
- Logoff(true);
- }
- request.Digest = null;
- throw;
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal void SessionSetup(ServerMessageBlock andx, ServerMessageBlock andxResponse
- )
- {
- lock (Transport())
- {
- NtlmContext nctx = null;
- SmbException ex = null;
- SmbComSessionSetupAndX request;
- SmbComSessionSetupAndXResponse response;
- byte[] token = new byte[0];
- int state = 10;
- while (ConnectionState != 0)
- {
- if (ConnectionState == 2 || ConnectionState == 3)
- {
- // connected or disconnecting
- return;
- }
- try
- {
- Runtime.Wait(transport);
- }
- catch (Exception ie)
- {
- throw new SmbException(ie.Message, ie);
- }
- }
- ConnectionState = 1;
- // trying ...
- try
- {
- transport.Connect();
- if (transport.Log.Level >= 4)
- {
- transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username + ",primaryDomain="
- + Auth.Domain);
- }
- Uid = 0;
- do
- {
- switch (state)
- {
- case 10:
- {
- if (Auth != NtlmPasswordAuthentication.Anonymous && transport.HasCapability(SmbConstants
- .CapExtendedSecurity))
- {
- state = 20;
- break;
- }
- request = new SmbComSessionSetupAndX(this, andx, Auth);
- response = new SmbComSessionSetupAndXResponse(andxResponse);
- if (transport.IsSignatureSetupRequired(Auth))
- {
- if (Auth.HashesExternal && NtlmPasswordAuthentication.DefaultPassword != NtlmPasswordAuthentication
- .Blank)
- {
- transport.GetSmbSession(NtlmPasswordAuthentication.Default).GetSmbTree(LogonShare
- , null).TreeConnect(null, null);
- }
- else
- {
- byte[] signingKey = Auth.GetSigningKey(transport.Server.EncryptionKey);
- request.Digest = new SigningDigest(signingKey, false);
- }
- }
- request.Auth = Auth;
- try
- {
- transport.Send(request, response);
- }
- catch (SmbAuthException sae)
- {
- throw;
- }
- catch (SmbException se)
- {
- ex = se;
- }
- if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth.
- Username) == false && transport.Server.Security != SmbConstants.SecurityShare &&
- Auth != NtlmPasswordAuthentication.Anonymous)
- {
- throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
- }
- if (ex != null)
- {
- throw ex;
- }
- Uid = response.Uid;
- if (request.Digest != null)
- {
- transport.Digest = request.Digest;
- }
- ConnectionState = 2;
- state = 0;
- break;
- }
-
- case 20:
- {
- if (nctx == null)
- {
- bool doSigning = (transport.Flags2 & SmbConstants.Flags2SecuritySignatures
- ) != 0;
- nctx = new NtlmContext(Auth, doSigning);
- }
- if (SmbTransport.LogStatic.Level >= 4)
- {
- SmbTransport.LogStatic.WriteLine(nctx);
- }
- if (nctx.IsEstablished())
- {
- NetbiosName = nctx.GetNetbiosName();
- ConnectionState = 2;
- state = 0;
- break;
- }
- try
- {
- token = nctx.InitSecContext(token, 0, token.Length);
- }
- catch (SmbException se)
- {
- try
- {
- transport.Disconnect(true);
- }
- catch (IOException)
- {
- }
- Uid = 0;
- throw;
- }
- if (token != null)
- {
- request = new SmbComSessionSetupAndX(this, null, token);
- response = new SmbComSessionSetupAndXResponse(null);
- if (transport.IsSignatureSetupRequired(Auth))
- {
- byte[] signingKey = nctx.GetSigningKey();
- if (signingKey != null)
- {
- request.Digest = new SigningDigest(signingKey, true);
- }
- }
- request.Uid = Uid;
- Uid = 0;
- try
- {
- transport.Send(request, response);
- }
- catch (SmbAuthException sae)
- {
- throw;
- }
- catch (SmbException se)
- {
- ex = se;
- try
- {
- transport.Disconnect(true);
- }
- catch (Exception)
- {
- }
- }
- if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth.
- Username) == false)
- {
- throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
- }
- if (ex != null)
- {
- throw ex;
- }
- Uid = response.Uid;
- if (request.Digest != null)
- {
- transport.Digest = request.Digest;
- }
- token = response.Blob;
- }
- break;
- }
-
- default:
- {
- throw new SmbException("Unexpected session setup state: " + state);
- }
- }
- }
- while (state != 0);
- }
- catch (SmbException se)
- {
- Logoff(true);
- ConnectionState = 0;
- throw;
- }
- finally
- {
- Runtime.NotifyAll(transport);
- }
- }
- }
-
- internal void Logoff(bool inError)
- {
- lock (Transport())
- {
- if (ConnectionState != 2)
- {
- // not-connected
- return;
- }
- ConnectionState = 3;
- // disconnecting
- NetbiosName = null;
-
- foreach (SmbTree t in Trees)
- {
- t.TreeDisconnect(inError);
- }
-
- if (!inError && transport.Server.Security != SmbConstants.SecurityShare)
- {
- SmbComLogoffAndX request = new SmbComLogoffAndX(null);
- request.Uid = Uid;
- try
- {
- transport.Send(request, null);
- }
- catch (SmbException)
- {
- }
- Uid = 0;
- }
- ConnectionState = 0;
- Runtime.NotifyAll(transport);
- }
- }
-
- public override string ToString()
- {
- return "SmbSession[accountName=" + Auth.Username + ",primaryDomain=" + Auth.Domain
- + ",uid=" + Uid + ",connectionState=" + ConnectionState + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs
deleted file mode 100644
index 811c76794..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- public class SmbShareInfo : IFileEntry
- {
- protected internal string NetName;
-
- protected internal int Type;
-
- protected internal string Remark;
-
- public SmbShareInfo()
- {
- }
-
- public SmbShareInfo(string netName, int type, string remark)
- {
- this.NetName = netName;
- this.Type = type;
- this.Remark = remark;
- }
-
- public virtual string GetName()
- {
- return NetName;
- }
-
- public new virtual int GetType()
- {
- switch (Type & unchecked(0xFFFF))
- {
- case 1:
- {
- return SmbFile.TypePrinter;
- }
-
- case 3:
- {
- return SmbFile.TypeNamedPipe;
- }
- }
- return SmbFile.TypeShare;
- }
-
- public virtual int GetAttributes()
- {
- return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
- }
-
- public virtual long CreateTime()
- {
- return 0L;
- }
-
- public virtual long LastModified()
- {
- return 0L;
- }
-
- public virtual long Length()
- {
- return 0L;
- }
-
- public override bool Equals(object obj)
- {
- if (obj is SmbShareInfo)
- {
- SmbShareInfo si = (SmbShareInfo)obj;
- return NetName.Equals(si.NetName);
- }
- return false;
- }
-
- public override int GetHashCode()
- {
- int hashCode = NetName.GetHashCode();
- return hashCode;
- }
-
- public override string ToString()
- {
- return "SmbShareInfo[" + "netName=" + NetName + ",type=0x" + Hexdump.ToHexString
- (Type, 8) + ",remark=" + Remark + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs
deleted file mode 100644
index 800d6d9bc..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs
+++ /dev/null
@@ -1,977 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using SharpCifs.Netbios;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-using SharpCifs.Util.Transport;
-
-namespace SharpCifs.Smb
-{
- public class SmbTransport : Transport
- {
- internal static readonly byte[] Buf = new byte[0xFFFF];
-
- internal static readonly SmbComNegotiate NegotiateRequest = new SmbComNegotiate(
- );
-
- internal static LogStream LogStatic = LogStream.GetInstance();
-
- internal static Hashtable DfsRoots = null;
-
-
- internal static SmbTransport GetSmbTransport(UniAddress address, int port
- )
- {
- lock (typeof(SmbTransport))
- {
- return GetSmbTransport(address, port, SmbConstants.Laddr, SmbConstants.Lport, null);
- }
- }
-
- internal static SmbTransport GetSmbTransport(UniAddress address, int port
- , IPAddress localAddr, int localPort, string hostName)
- {
- lock (typeof(SmbTransport))
- {
- SmbTransport conn;
-
- lock (SmbConstants.Connections)
- {
- if (SmbConstants.SsnLimit != 1)
- {
- conn =
- SmbConstants.Connections.FirstOrDefault(
- c =>
- c.Matches(address, port, localAddr, localPort, hostName) &&
- (SmbConstants.SsnLimit ==
- 0 || c.Sessions.Count < SmbConstants.SsnLimit));
-
- if (conn != null)
- {
- return conn;
- }
-
- }
-
- conn = new SmbTransport(address, port, localAddr, localPort);
- SmbConstants.Connections.Insert(0, conn);
- }
- return conn;
- }
- }
-
- internal class ServerData
- {
- internal byte Flags;
-
- internal int Flags2;
-
- internal int MaxMpxCount;
-
- internal int MaxBufferSize;
-
- internal int SessionKey;
-
- internal int Capabilities;
-
- internal string OemDomainName;
-
- internal int SecurityMode;
-
- internal int Security;
-
- internal bool EncryptedPasswords;
-
- internal bool SignaturesEnabled;
-
- internal bool SignaturesRequired;
-
- internal int MaxNumberVcs;
-
- internal int MaxRawSize;
-
- internal long ServerTime;
-
- internal int ServerTimeZone;
-
- internal int EncryptionKeyLength;
-
- internal byte[] EncryptionKey;
-
- internal byte[] Guid;
-
- internal ServerData(SmbTransport enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly SmbTransport _enclosing;
- }
-
- internal IPAddress LocalAddr;
-
- internal int LocalPort;
-
- internal UniAddress Address;
-
- internal SocketEx Socket;
-
- internal int Port;
-
- internal int Mid;
-
- internal OutputStream Out;
-
- internal InputStream In;
-
- internal byte[] Sbuf = new byte[512];
-
- internal SmbComBlankResponse Key = new SmbComBlankResponse();
-
- internal long SessionExpiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout;
-
- internal List<object> Referrals = new List<object>();
-
- internal SigningDigest Digest;
-
- internal List<SmbSession> Sessions = new List<SmbSession>();
-
- internal ServerData Server;
-
- internal int Flags2 = SmbConstants.Flags2;
-
- internal int MaxMpxCount = SmbConstants.MaxMpxCount;
-
- internal int SndBufSize = SmbConstants.SndBufSize;
-
- internal int RcvBufSize = SmbConstants.RcvBufSize;
-
- internal int Capabilities = SmbConstants.Capabilities;
-
- internal int SessionKey = 0x00000000;
-
- internal bool UseUnicode = SmbConstants.UseUnicode;
-
- internal string TconHostName;
-
- internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort
- )
- {
- Server = new ServerData(this);
- this.Address = address;
- this.Port = port;
- this.LocalAddr = localAddr;
- this.LocalPort = localPort;
- }
-
- internal virtual SmbSession GetSmbSession()
- {
- lock (this)
- {
- return GetSmbSession(new NtlmPasswordAuthentication(null, null, null));
- }
- }
-
- internal virtual SmbSession GetSmbSession(NtlmPasswordAuthentication auth)
- {
- lock (this)
- {
- SmbSession ssn;
- long now;
-
- ssn = Sessions.FirstOrDefault(s => s.Matches(auth));
- if (ssn != null)
- {
- ssn.Auth = auth;
- return ssn;
- }
-
- if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis()))
- {
- SessionExpiration = now + SmbConstants.SoTimeout;
-
- foreach (var session in Sessions.Where(s => s.Expiration < now))
- {
- session.Logoff(false);
- }
- }
- ssn = new SmbSession(Address, Port, LocalAddr, LocalPort, auth);
- ssn.transport = this;
- Sessions.Add(ssn);
- return ssn;
- }
- }
-
- internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr,
- int localPort, string hostName)
- {
- if (hostName == null)
- {
- hostName = address.GetHostName();
- }
- return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && address.Equals(this.Address) && (port == -1 || port == this.Port
- || (port == 445 && this.Port == 139)) && (localAddr == this.LocalAddr || (localAddr
- != null && localAddr.Equals(this.LocalAddr))) && localPort == this.LocalPort;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual bool HasCapability(int cap)
- {
- try
- {
- Connect(SmbConstants.ResponseTimeout);
- }
- catch (IOException ioe)
- {
- throw new SmbException(ioe.Message, ioe);
- }
- return (Capabilities & cap) == cap;
- }
-
- internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
- {
- return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest ==
- null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null
- .Equals(auth) == false;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- internal virtual void Ssn139()
- {
- Name calledName = new Name(Address.FirstCalledName(), 0x20, null
- );
- do
- {
- Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- if (LocalAddr != null)
- {
- Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
- }
-
- Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout);
- Socket.SoTimeOut = SmbConstants.SoTimeout;
-
- Out = Socket.GetOutputStream();
- In = Socket.GetInputStream();
- SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName
- ());
- Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
- if (Readn(In, Sbuf, 0, 4) < 4)
- {
- try
- {
- //Socket.`Close` method deleted
- //Socket.Close();
- Socket.Dispose();
- }
- catch (IOException)
- {
- }
- throw new SmbException("EOF during NetBIOS session request");
- }
- switch (Sbuf[0] & 0xFF)
- {
- case SessionServicePacket.PositiveSessionResponse:
- {
- if (Log.Level >= 4)
- {
- Log.WriteLine("session established ok with " + Address);
- }
- return;
- }
-
- case SessionServicePacket.NegativeSessionResponse:
- {
- int errorCode = In.Read() & 0xFF;
- switch (errorCode)
- {
- case NbtException.CalledNotPresent:
- case NbtException.NotListeningCalled:
- {
- //Socket.`Close` method deleted
- //Socket.Close();
- Socket.Dispose();
- break;
- }
-
- default:
- {
- Disconnect(true);
- throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
- }
- }
- break;
- }
-
- case -1:
- {
- Disconnect(true);
- throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
- );
- }
-
- default:
- {
- Disconnect(true);
- throw new NbtException(NbtException.ErrSsnSrvc, 0);
- }
- }
- }
- while ((calledName.name = Address.NextCalledName()) != null);
- throw new IOException("Failed to establish session with " + Address);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- private void Negotiate(int port, ServerMessageBlock resp)
- {
- lock (Sbuf)
- {
- if (port == 139)
- {
- Ssn139();
- }
- else
- {
- if (port == -1)
- {
- port = SmbConstants.DefaultPort;
- }
- // 445
- Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- if (LocalAddr != null)
- {
- Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
- }
-
- Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), port), SmbConstants.ConnTimeout);
- Socket.SoTimeOut = SmbConstants.SoTimeout;
- Out = Socket.GetOutputStream();
- In = Socket.GetInputStream();
- }
- if (++Mid == 32000)
- {
- Mid = 1;
- }
- NegotiateRequest.Mid = Mid;
- int n = NegotiateRequest.Encode(Sbuf, 4);
- Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0);
- if (Log.Level >= 4)
- {
- Log.WriteLine(NegotiateRequest);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, Sbuf, 4, n);
- }
- }
- Out.Write(Sbuf, 0, 4 + n);
- Out.Flush();
- if (PeekKey() == null)
- {
- throw new IOException("transport closed in negotiate");
- }
- int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
- if (size < 33 || (4 + size) > Sbuf.Length)
- {
- throw new IOException("Invalid payload size: " + size);
- }
- Readn(In, Sbuf, 4 + 32, size - 32);
- resp.Decode(Sbuf, 4);
- if (Log.Level >= 4)
- {
- Log.WriteLine(resp);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, Sbuf, 4, n);
- }
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- public virtual void Connect()
- {
- try
- {
- base.Connect(SmbConstants.ResponseTimeout);
- }
- catch (TransportException te)
- {
- throw new SmbException("Failed to connect: " + Address, te);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoConnect()
- {
- SmbComNegotiateResponse resp = new SmbComNegotiateResponse(Server);
- try
- {
- Negotiate(Port, resp);
- }
- catch (ConnectException)
- {
- Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort;
- Negotiate(Port, resp);
- }
- if (resp.DialectIndex > 10)
- {
- throw new SmbException("This client does not support the negotiated dialect.");
- }
- if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server
- .EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0)
- {
- throw new SmbException("Unexpected encryption key length: " + Server.EncryptionKeyLength
- );
- }
- TconHostName = Address.GetHostName();
- if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref))
- {
- Flags2 |= SmbConstants.Flags2SecuritySignatures;
- }
- else
- {
- Flags2 &= 0xFFFF ^ SmbConstants.Flags2SecuritySignatures;
- }
- MaxMpxCount = Math.Min(MaxMpxCount, Server.MaxMpxCount);
- if (MaxMpxCount < 1)
- {
- MaxMpxCount = 1;
- }
- SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize);
- Capabilities &= Server.Capabilities;
- if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity)
- {
- Capabilities |= SmbConstants.CapExtendedSecurity;
- }
- // & doesn't copy high bit
- if ((Capabilities & SmbConstants.CapUnicode) == 0)
- {
- // server doesn't want unicode
- if (SmbConstants.ForceUnicode)
- {
- Capabilities |= SmbConstants.CapUnicode;
- }
- else
- {
- UseUnicode = false;
- Flags2 &= 0xFFFF ^ SmbConstants.Flags2Unicode;
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoDisconnect(bool hard)
- {
- try
- {
- foreach (var ssn in Sessions)
- {
- ssn.Logoff(hard);
- }
-
- Out.Close();
- In.Close();
-
- //Socket.`Close` method deleted
- //Socket.Close();
- Socket.Dispose();
- }
- finally
- {
- Digest = null;
- Socket = null;
- TconHostName = null;
- }
-
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void MakeKey(ServerMessageBlock request)
- {
- if (++Mid == 32000)
- {
- Mid = 1;
- }
- request.Mid = Mid;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override ServerMessageBlock PeekKey()
- {
- int n;
- do
- {
- if ((n = Readn(In, Sbuf, 0, 4)) < 4)
- {
- return null;
- }
- }
- while (Sbuf[0] == 0x85);
- if ((n = Readn(In, Sbuf, 4, 32)) < 32)
- {
- return null;
- }
- if (Log.Level >= 4)
- {
- Log.WriteLine("New data read: " + this);
- Hexdump.ToHexdump(Log, Sbuf, 4, 32);
- }
- for (; ; )
- {
- if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 &&
- Sbuf[4] == 0xFF &&
- Sbuf[5] == 'S' &&
- Sbuf[6] == 'M' &&
- Sbuf[7] == 'B')
- {
- break;
- }
- for (int i = 0; i < 35; i++)
- {
- Sbuf[i] = Sbuf[i + 1];
- }
- int b;
- if ((b = In.Read()) == -1)
- {
- return null;
- }
- Sbuf[35] = unchecked((byte)b);
- }
- Key.Mid = Encdec.Dec_uint16le(Sbuf, 34) & 0xFFFF;
- return Key;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoSend(ServerMessageBlock request)
- {
- lock (Buf)
- {
- ServerMessageBlock smb = request;
- int n = smb.Encode(Buf, 4);
- Encdec.Enc_uint32be(n & 0xFFFF, Buf, 0);
- if (Log.Level >= 4)
- {
- do
- {
- Log.WriteLine(smb);
- }
- while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx
- ) != null);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, Buf, 4, n);
- }
- }
- Out.Write(Buf, 0, 4 + n);
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal virtual void DoSend0(ServerMessageBlock request)
- {
- try
- {
- DoSend(request);
- }
- catch (IOException ioe)
- {
- if (Log.Level > 2)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- try
- {
- Disconnect(true);
- }
- catch (IOException ioe2)
- {
- Runtime.PrintStackTrace(ioe2, Log);
- }
- throw;
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoRecv(Response response)
- {
- ServerMessageBlock resp = (ServerMessageBlock)response;
- resp.UseUnicode = UseUnicode;
- resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity;
- lock (Buf)
- {
- Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength);
- int size = Encdec.Dec_uint16be(Buf, 2) & 0xFFFF;
- if (size < (SmbConstants.HeaderLength + 1) || (4 + size) > RcvBufSize)
- {
- throw new IOException("Invalid payload size: " + size);
- }
- int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF));
- if (resp.Command == ServerMessageBlock.SmbComReadAndx && (errorCode == 0 || errorCode
- == unchecked((int)(0x80000005))))
- {
- // overflow indicator normal for pipe
- SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp;
- int off = SmbConstants.HeaderLength;
- Readn(In, Buf, 4 + off, 27);
- off += 27;
- resp.Decode(Buf, 4);
- int pad = r.DataOffset - off;
- if (r.ByteCount > 0 && pad > 0 && pad < 4)
- {
- Readn(In, Buf, 4 + off, pad);
- }
- if (r.DataLength > 0)
- {
- Readn(In, r.B, r.Off, r.DataLength);
- }
- }
- else
- {
- Readn(In, Buf, 4 + 32, size - 32);
- resp.Decode(Buf, 4);
- if (resp is SmbComTransactionResponse)
- {
- ((SmbComTransactionResponse)resp).Current();
- }
- }
- if (Digest != null && resp.ErrorCode == 0)
- {
- Digest.Verify(Buf, 4, resp);
- }
- if (Log.Level >= 4)
- {
- Log.WriteLine(response);
- if (Log.Level >= 6)
- {
- Hexdump.ToHexdump(Log, Buf, 4, size);
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal override void DoSkip()
- {
- int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
- if (size < 33 || (4 + size) > RcvBufSize)
- {
- In.Skip(In.Available());
- }
- else
- {
- In.Skip(size - 32);
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void CheckStatus(ServerMessageBlock req, ServerMessageBlock resp
- )
- {
- resp.ErrorCode = SmbException.GetStatusByCode(resp.ErrorCode);
- switch (resp.ErrorCode)
- {
- case NtStatus.NtStatusOk:
- {
- break;
- }
-
- case NtStatus.NtStatusAccessDenied:
- case NtStatus.NtStatusWrongPassword:
- case NtStatus.NtStatusLogonFailure:
- case NtStatus.NtStatusAccountRestriction:
- case NtStatus.NtStatusInvalidLogonHours:
- case NtStatus.NtStatusInvalidWorkstation:
- case NtStatus.NtStatusPasswordExpired:
- case NtStatus.NtStatusAccountDisabled:
- case NtStatus.NtStatusAccountLockedOut:
- case NtStatus.NtStatusTrustedDomainFailure:
- {
- throw new SmbAuthException(resp.ErrorCode);
- }
-
- case NtStatus.NtStatusPathNotCovered:
- {
- if (req.Auth == null)
- {
- throw new SmbException(resp.ErrorCode, null);
- }
- DfsReferral dr = GetDfsReferrals(req.Auth, req.Path, 1);
- if (dr == null)
- {
- throw new SmbException(resp.ErrorCode, null);
- }
- SmbFile.Dfs.Insert(req.Path, dr);
- throw dr;
- }
-
- case unchecked((int)(0x80000005)):
- {
- break;
- }
-
- case NtStatus.NtStatusMoreProcessingRequired:
- {
- break;
- }
-
- default:
- {
- throw new SmbException(resp.ErrorCode, null);
- }
- }
- if (resp.VerifyFailed)
- {
- throw new SmbException("Signature verification failed.");
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
- )
- {
- Connect();
- request.Flags2 |= Flags2;
- request.UseUnicode = UseUnicode;
- request.Response = response;
- if (request.Digest == null)
- {
- request.Digest = Digest;
- }
- try
- {
- if (response == null)
- {
- DoSend0(request);
- return;
- }
- if (request is SmbComTransaction)
- {
- response.Command = request.Command;
- SmbComTransaction req = (SmbComTransaction)request;
- SmbComTransactionResponse resp = (SmbComTransactionResponse)response;
- req.MaxBufferSize = SndBufSize;
- resp.Reset();
- try
- {
- BufferCache.GetBuffers(req, resp);
- req.Current();
- if (req.MoveNext())
- {
- SmbComBlankResponse interim = new SmbComBlankResponse();
- Sendrecv(req, interim, SmbConstants.ResponseTimeout);
- if (interim.ErrorCode != 0)
- {
- CheckStatus(req, interim);
- }
- req.Current();
- }
- else
- {
- MakeKey(req);
- }
- lock (this)
- {
- response.Received = false;
- resp.IsReceived = false;
- try
- {
- ResponseMap.Put(req, resp);
- do
- {
- DoSend0(req);
- }
- while (req.MoveNext() && req.Current() != null);
- long timeout = SmbConstants.ResponseTimeout;
- resp.Expiration = Runtime.CurrentTimeMillis() + timeout;
- while (resp.MoveNext())
- {
- Runtime.Wait(this, timeout);
- timeout = resp.Expiration - Runtime.CurrentTimeMillis();
- if (timeout <= 0)
- {
- throw new TransportException(this + " timedout waiting for response to " + req);
- }
- }
- if (response.ErrorCode != 0)
- {
- CheckStatus(req, resp);
- }
- }
- catch (Exception ie)
- {
- if (ie is SmbException)
- {
- throw;
- }
- else
- {
- throw new TransportException(ie);
- }
- }
- finally
- {
- //Sharpen.Collections.Remove<Hashtable, SmbComTransaction>(response_map, req);
- ResponseMap.Remove(req);
- }
- }
- }
- finally
- {
- BufferCache.ReleaseBuffer(req.TxnBuf);
- BufferCache.ReleaseBuffer(resp.TxnBuf);
- }
- }
- else
- {
- response.Command = request.Command;
- Sendrecv(request, response, SmbConstants.ResponseTimeout);
- }
- }
- catch (SmbException se)
- {
- throw;
- }
- catch (IOException ioe)
- {
- throw new SmbException(ioe.Message, ioe);
- }
- CheckStatus(request, response);
- }
-
- public override string ToString()
- {
- return base.ToString() + "[" + Address + ":" + Port + "]";
- }
-
- internal virtual void DfsPathSplit(string path, string[] result)
- {
- int ri = 0;
- int rlast = result.Length - 1;
- int i = 0;
- int b = 0;
- int len = path.Length;
- do
- {
- if (ri == rlast)
- {
- result[rlast] = Runtime.Substring(path, b);
- return;
- }
- if (i == len || path[i] == '\\')
- {
- result[ri++] = Runtime.Substring(path, b, i);
- b = i + 1;
- }
- }
- while (i++ < len);
- while (ri < result.Length)
- {
- result[ri++] = string.Empty;
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string
- path, int rn)
- {
- SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
- Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
- ipc.Send(new Trans2GetDfsReferral(path), resp);
- if (resp.NumReferrals == 0)
- {
- return null;
- }
- if (rn == 0 || resp.NumReferrals < rn)
- {
- rn = resp.NumReferrals;
- }
- DfsReferral dr = new DfsReferral();
- string[] arr = new string[4];
- long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
- int di = 0;
- for (; ; )
- {
- dr.ResolveHashes = auth.HashesExternal;
- dr.Ttl = resp.Referrals[di].Ttl;
- dr.Expiration = expiration;
- if (path.Equals(string.Empty))
- {
- dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
- }
- else
- {
- DfsPathSplit(resp.Referrals[di].Node, arr);
- dr.Server = arr[1];
- dr.Share = arr[2];
- dr.Path = arr[3];
- }
- dr.PathConsumed = resp.PathConsumed;
- di++;
- if (di == rn)
- {
- break;
- }
- dr.Append(new DfsReferral());
- dr = dr.Next;
- }
- return dr.Next;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth,
- string path, int rn)
- {
- SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
- Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
- ipc.Send(new Trans2GetDfsReferral(path), resp);
- if (rn == 0 || resp.NumReferrals < rn)
- {
- rn = resp.NumReferrals;
- }
- DfsReferral[] drs = new DfsReferral[rn];
- string[] arr = new string[4];
- long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
- for (int di = 0; di < drs.Length; di++)
- {
- DfsReferral dr = new DfsReferral();
- dr.ResolveHashes = auth.HashesExternal;
- dr.Ttl = resp.Referrals[di].Ttl;
- dr.Expiration = expiration;
- if (path.Equals(string.Empty))
- {
- dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
- }
- else
- {
- DfsPathSplit(resp.Referrals[di].Node, arr);
- dr.Server = arr[1];
- dr.Share = arr[2];
- dr.Path = arr[3];
- }
- dr.PathConsumed = resp.PathConsumed;
- drs[di] = dr;
- }
- return drs;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs
deleted file mode 100644
index 8dc068c4c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs
+++ /dev/null
@@ -1,250 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- class SmbTree
- {
- private static int _treeConnCounter;
-
- internal int ConnectionState;
-
- internal int Tid;
-
- internal string Share;
-
- internal string Service = "?????";
-
- internal string Service0;
-
- internal SmbSession Session;
-
- internal bool InDfs;
-
- internal bool InDomainDfs;
-
- internal int TreeNum;
-
- internal SmbTree(SmbSession session, string share, string service)
- {
- // used by SmbFile.isOpen
- this.Session = session;
- this.Share = share.ToUpper();
- if (service != null && service.StartsWith("??") == false)
- {
- this.Service = service;
- }
- Service0 = this.Service;
- ConnectionState = 0;
- }
-
- internal virtual bool Matches(string share, string service)
- {
- return Runtime.EqualsIgnoreCase(this.Share, share) && (service == null ||
- service.StartsWith("??") || Runtime.EqualsIgnoreCase(this.Service, service
- ));
- }
-
- public override bool Equals(object obj)
- {
- if (obj is SmbTree)
- {
- SmbTree tree = (SmbTree)obj;
- return Matches(tree.Share, tree.Service);
- }
- return false;
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
- )
- {
- lock (Session.Transport())
- {
- if (response != null)
- {
- response.Received = false;
- }
- TreeConnect(request, response);
- if (request == null || (response != null && response.Received))
- {
- return;
- }
- if (Service.Equals("A:") == false)
- {
- switch (request.Command)
- {
- case ServerMessageBlock.SmbComOpenAndx:
- case ServerMessageBlock.SmbComNtCreateAndx:
- case ServerMessageBlock.SmbComReadAndx:
- case ServerMessageBlock.SmbComWriteAndx:
- case ServerMessageBlock.SmbComClose:
- case ServerMessageBlock.SmbComTreeDisconnect:
- {
- break;
- }
-
- case ServerMessageBlock.SmbComTransaction:
- case ServerMessageBlock.SmbComTransaction2:
- {
- switch (((SmbComTransaction)request).SubCommand & unchecked(0xFF))
- {
- case SmbComTransaction.NetShareEnum:
- case SmbComTransaction.NetServerEnum2:
- case SmbComTransaction.NetServerEnum3:
- case SmbComTransaction.TransPeekNamedPipe:
- case SmbComTransaction.TransWaitNamedPipe:
- case SmbComTransaction.TransCallNamedPipe:
- case SmbComTransaction.TransTransactNamedPipe:
- case SmbComTransaction.Trans2GetDfsReferral:
- {
- break;
- }
-
- default:
- {
- throw new SmbException("Invalid operation for " + Service + " service");
- }
- }
- break;
- }
-
- default:
- {
- throw new SmbException("Invalid operation for " + Service + " service" + request);
- }
- }
- }
- request.Tid = Tid;
- if (InDfs && !Service.Equals("IPC") && !string.IsNullOrEmpty(request.Path))
- {
- request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs;
- request.Path = '\\' + Session.Transport().TconHostName + '\\' + Share + request.Path;
- }
- try
- {
- Session.Send(request, response);
- }
- catch (SmbException se)
- {
- if (se.GetNtStatus() == NtStatus.NtStatusNetworkNameDeleted)
- {
- TreeDisconnect(true);
- }
- throw;
- }
- }
- }
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- internal virtual void TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse
- )
- {
- lock (Session.Transport())
- {
- string unc;
- while (ConnectionState != 0)
- {
- if (ConnectionState == 2 || ConnectionState == 3)
- {
- // connected or disconnecting
- return;
- }
- try
- {
- Runtime.Wait(Session.transport);
- }
- catch (Exception ie)
- {
- throw new SmbException(ie.Message, ie);
- }
- }
- ConnectionState = 1;
- // trying ...
- try
- {
- Session.transport.Connect();
- unc = "\\\\" + Session.transport.TconHostName + '\\' + Share;
- Service = Service0;
- if (Session.transport.Log.Level >= 4)
- {
- Session.transport.Log.WriteLine("treeConnect: unc=" + unc + ",service=" + Service
- );
- }
- SmbComTreeConnectAndXResponse response = new SmbComTreeConnectAndXResponse(andxResponse
- );
- SmbComTreeConnectAndX request = new SmbComTreeConnectAndX(Session, unc, Service,
- andx);
- Session.Send(request, response);
- Tid = response.Tid;
- Service = response.Service;
- InDfs = response.ShareIsInDfs;
- TreeNum = _treeConnCounter++;
- ConnectionState = 2;
- }
- catch (SmbException se)
- {
- // connected
- TreeDisconnect(true);
- ConnectionState = 0;
- throw;
- }
- }
- }
-
- internal virtual void TreeDisconnect(bool inError)
- {
- lock (Session.Transport())
- {
- if (ConnectionState != 2)
- {
- // not-connected
- return;
- }
- ConnectionState = 3;
- // disconnecting
- if (!inError && Tid != 0)
- {
- try
- {
- Send(new SmbComTreeDisconnect(), null);
- }
- catch (SmbException se)
- {
- if (Session.transport.Log.Level > 1)
- {
- Runtime.PrintStackTrace(se, Session.transport.Log);
- }
- }
- }
- InDfs = false;
- InDomainDfs = false;
- ConnectionState = 0;
- Runtime.NotifyAll(Session.transport);
- }
- }
-
- public override string ToString()
- {
- return "SmbTree[share=" + Share + ",service=" + Service + ",tid=" + Tid + ",inDfs="
- + InDfs + ",inDomainDfs=" + InDomainDfs + ",connectionState=" + ConnectionState
- + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs
deleted file mode 100644
index 2ef874882..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2FindFirst2 : SmbComTransaction
- {
- private const int FlagsCloseAfterThisRequest = unchecked(0x01);
-
- private const int FlagsCloseIfEndReached = unchecked(0x02);
-
- private const int FlagsReturnResumeKeys = unchecked(0x04);
-
- private const int FlagsResumeFromPreviousEnd = unchecked(0x08);
-
- private const int FlagsFindWithBackupIntent = unchecked(0x10);
-
- private const int DefaultListSize = 65535;
-
- private const int DefaultListCount = 200;
-
- private int _searchAttributes;
-
- private int _flags;
-
- private int _informationLevel;
-
- private int _searchStorageType = 0;
-
- private string _wildcard;
-
- internal const int SmbInfoStandard = 1;
-
- internal const int SmbInfoQueryEaSize = 2;
-
- internal const int SmbInfoQueryEasFromList = 3;
-
- internal const int SmbFindFileDirectoryInfo = unchecked(0x101);
-
- internal const int SmbFindFileFullDirectoryInfo = unchecked(0x102);
-
- internal const int SmbFileNamesInfo = unchecked(0x103);
-
- internal const int SmbFileBothDirectoryInfo = unchecked(0x104);
-
- internal static readonly int ListSize = Config.GetInt("jcifs.smb.client.listSize"
- , DefaultListSize);
-
- internal static readonly int ListCount = Config.GetInt("jcifs.smb.client.listCount"
- , DefaultListCount);
-
- internal Trans2FindFirst2(string filename, string wildcard, int searchAttributes)
- {
- // flags
- // information levels
- if (filename.Equals("\\"))
- {
- Path = filename;
- }
- else
- {
- Path = filename + "\\";
- }
- this._wildcard = wildcard;
- this._searchAttributes = searchAttributes & unchecked(0x37);
- Command = SmbComTransaction2;
- SubCommand = Trans2FindFirst2;
- _flags = unchecked(0x00);
- _informationLevel = SmbFileBothDirectoryInfo;
- TotalDataCount = 0;
- MaxParameterCount = 10;
- MaxDataCount = ListSize;
- MaxSetupCount = 0;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_searchAttributes, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(ListCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_flags, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_informationLevel, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_searchStorageType, dst, dstIndex);
- dstIndex += 4;
- dstIndex += WriteString(Path + _wildcard, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2FindFirst2[" + base.ToString() + ",searchAttributes=0x"
- + Hexdump.ToHexString(_searchAttributes, 2) + ",searchCount=" + ListCount + ",flags=0x"
- + Hexdump.ToHexString(_flags, 2) + ",informationLevel=0x" + Hexdump.ToHexString(
- _informationLevel, 3) + ",searchStorageType=" + _searchStorageType + ",filename="
- + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs
deleted file mode 100644
index 71f780ff3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs
+++ /dev/null
@@ -1,262 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2FindFirst2Response : SmbComTransactionResponse
- {
- internal const int SmbInfoStandard = 1;
-
- internal const int SmbInfoQueryEaSize = 2;
-
- internal const int SmbInfoQueryEasFromList = 3;
-
- internal const int SmbFindFileDirectoryInfo = unchecked(0x101);
-
- internal const int SmbFindFileFullDirectoryInfo = unchecked(0x102);
-
- internal const int SmbFileNamesInfo = unchecked(0x103);
-
- internal const int SmbFileBothDirectoryInfo = unchecked(0x104);
-
- internal class SmbFindFileBothDirectoryInfo : IFileEntry
- {
- internal int NextEntryOffset;
-
- internal int FileIndex;
-
- internal long CreationTime;
-
- internal long LastAccessTime;
-
- internal long LastWriteTime;
-
- internal long ChangeTime;
-
- internal long EndOfFile;
-
- internal long AllocationSize;
-
- internal int ExtFileAttributes;
-
- internal int FileNameLength;
-
- internal int EaSize;
-
- internal int ShortNameLength;
-
- internal string ShortName;
-
- internal string Filename;
-
- // information levels
- public virtual string GetName()
- {
- return Filename;
- }
-
- public virtual int GetType()
- {
- return SmbFile.TypeFilesystem;
- }
-
- public virtual int GetAttributes()
- {
- return ExtFileAttributes;
- }
-
- public virtual long CreateTime()
- {
- return CreationTime;
- }
-
- public virtual long LastModified()
- {
- return LastWriteTime;
- }
-
- public virtual long Length()
- {
- return EndOfFile;
- }
-
- public override string ToString()
- {
- return "SmbFindFileBothDirectoryInfo[" + "nextEntryOffset=" + NextEntryOffset
- + ",fileIndex=" + FileIndex + ",creationTime=" + Extensions.CreateDate
- (CreationTime) + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime
- ) + ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",changeTime="
- + Extensions.CreateDate(ChangeTime) + ",endOfFile=" + EndOfFile
- + ",allocationSize=" + AllocationSize + ",extFileAttributes=" + ExtFileAttributes
- + ",fileNameLength=" + FileNameLength + ",eaSize=" + EaSize + ",shortNameLength="
- + ShortNameLength + ",shortName=" + ShortName + ",filename=" + Filename
- + "]";
- }
-
- internal SmbFindFileBothDirectoryInfo(Trans2FindFirst2Response enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly Trans2FindFirst2Response _enclosing;
- }
-
- internal int Sid;
-
- internal bool IsEndOfSearch;
-
- internal int EaErrorOffset;
-
- internal int LastNameOffset;
-
- internal int LastNameBufferIndex;
-
- internal string LastName;
-
- internal int ResumeKey;
-
- public Trans2FindFirst2Response()
- {
- Command = SmbComTransaction2;
- SubCommand = Smb.SmbComTransaction.Trans2FindFirst2;
- }
-
- internal virtual string ReadString(byte[] src, int srcIndex, int len)
- {
- string str = null;
- try
- {
- if (UseUnicode)
- {
- // should Unicode alignment be corrected for here?
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
- }
- else
- {
- if (len > 0 && src[srcIndex + len - 1] == '\0')
- {
- len--;
- }
- str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding
- );
- }
- }
- catch (UnsupportedEncodingException uee)
- {
- if (Log.Level > 1)
- {
- Runtime.PrintStackTrace(uee, Log);
- }
- }
- return str;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- int start = bufferIndex;
- if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2)
- {
- Sid = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- }
- NumEntries = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- IsEndOfSearch = (buffer[bufferIndex] & unchecked(0x01)) == unchecked(0x01) ? true : false;
- bufferIndex += 2;
- EaErrorOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- LastNameOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- return bufferIndex - start;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- SmbFindFileBothDirectoryInfo e;
- LastNameBufferIndex = bufferIndex + LastNameOffset;
- Results = new SmbFindFileBothDirectoryInfo[NumEntries];
- for (int i = 0; i < NumEntries; i++)
- {
- Results[i] = e = new SmbFindFileBothDirectoryInfo(this);
- e.NextEntryOffset = ReadInt4(buffer, bufferIndex);
- e.FileIndex = ReadInt4(buffer, bufferIndex + 4);
- e.CreationTime = ReadTime(buffer, bufferIndex + 8);
- // e.lastAccessTime = readTime( buffer, bufferIndex + 16 );
- e.LastWriteTime = ReadTime(buffer, bufferIndex + 24);
- // e.changeTime = readTime( buffer, bufferIndex + 32 );
- e.EndOfFile = ReadInt8(buffer, bufferIndex + 40);
- // e.allocationSize = readInt8( buffer, bufferIndex + 48 );
- e.ExtFileAttributes = ReadInt4(buffer, bufferIndex + 56);
- e.FileNameLength = ReadInt4(buffer, bufferIndex + 60);
- // e.eaSize = readInt4( buffer, bufferIndex + 64 );
- // e.shortNameLength = buffer[bufferIndex + 68] & 0xFF;
- // e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength );
- e.Filename = ReadString(buffer, bufferIndex + 94, e.FileNameLength);
- if (LastNameBufferIndex >= bufferIndex && (e.NextEntryOffset == 0 || LastNameBufferIndex
- < (bufferIndex + e.NextEntryOffset)))
- {
- LastName = e.Filename;
- ResumeKey = e.FileIndex;
- }
- bufferIndex += e.NextEntryOffset;
- }
- //return bufferIndex - start;
- return DataCount;
- }
-
- public override string ToString()
- {
- string c;
- if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2)
- {
- c = "Trans2FindFirst2Response[";
- }
- else
- {
- c = "Trans2FindNext2Response[";
- }
- return c + base.ToString() + ",sid=" + Sid + ",searchCount=" + NumEntries
- + ",isEndOfSearch=" + IsEndOfSearch + ",eaErrorOffset=" + EaErrorOffset + ",lastNameOffset="
- + LastNameOffset + ",lastName=" + LastName + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs
deleted file mode 100644
index cb860f799..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs
+++ /dev/null
@@ -1,109 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2FindNext2 : SmbComTransaction
- {
- private int _sid;
-
- private int _informationLevel;
-
- private int _resumeKey;
-
- private int _flags;
-
- private string _filename;
-
- internal Trans2FindNext2(int sid, int resumeKey, string filename)
- {
- this._sid = sid;
- this._resumeKey = resumeKey;
- this._filename = filename;
- Command = SmbComTransaction2;
- SubCommand = Trans2FindNext2;
- _informationLevel = Smb.Trans2FindFirst2.SmbFileBothDirectoryInfo;
- _flags = unchecked(0x00);
- MaxParameterCount = 8;
- MaxDataCount = Smb.Trans2FindFirst2.ListSize;
- MaxSetupCount = 0;
- }
-
- internal override void Reset(int resumeKey, string lastName)
- {
- base.Reset();
- this._resumeKey = resumeKey;
- _filename = lastName;
- Flags2 = 0;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_sid, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(Smb.Trans2FindFirst2.ListCount, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(_informationLevel, dst, dstIndex);
- dstIndex += 2;
- WriteInt4(_resumeKey, dst, dstIndex);
- dstIndex += 4;
- WriteInt2(_flags, dst, dstIndex);
- dstIndex += 2;
- dstIndex += WriteString(_filename, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2FindNext2[" + base.ToString() + ",sid=" + _sid + ",searchCount="
- + Smb.Trans2FindFirst2.ListSize + ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel
- , 3) + ",resumeKey=0x" + Hexdump.ToHexString(_resumeKey, 4) + ",flags=0x" + Hexdump
- .ToHexString(_flags, 2) + ",filename=" + _filename + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs
deleted file mode 100644
index c83de7973..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class Trans2GetDfsReferral : SmbComTransaction
- {
- private int _maxReferralLevel = 3;
-
- internal Trans2GetDfsReferral(string filename)
- {
- Path = filename;
- Command = SmbComTransaction2;
- SubCommand = Trans2GetDfsReferral;
- TotalDataCount = 0;
- MaxParameterCount = 0;
- MaxDataCount = 4096;
- MaxSetupCount = unchecked(unchecked(0x00));
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_maxReferralLevel, dst, dstIndex);
- dstIndex += 2;
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2GetDfsReferral[" + base.ToString() + ",maxReferralLevel=0x"
- + _maxReferralLevel + ",filename=" + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs
deleted file mode 100644
index 5fa4a795d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs
+++ /dev/null
@@ -1,179 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2GetDfsReferralResponse : SmbComTransactionResponse
- {
- internal class Referral
- {
- private int _version;
-
- private int _size;
-
- private int _serverType;
-
- private int _flags;
-
- private int _proximity;
-
- private int _pathOffset;
-
- private int _altPathOffset;
-
- private int _nodeOffset;
-
- private string _altPath;
-
- internal int Ttl;
-
- internal string Path;
-
- internal string Node;
-
- internal virtual int ReadWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- _version = ReadInt2(buffer, bufferIndex);
- if (_version != 3 && _version != 1)
- {
- throw new RuntimeException("Version " + _version + " referral not supported. Please report this to jcifs at samba dot org."
- );
- }
- bufferIndex += 2;
- _size = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _serverType = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _flags = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if (_version == 3)
- {
- _proximity = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Ttl = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _pathOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _altPathOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _nodeOffset = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- Path = _enclosing.ReadString(buffer, start + _pathOffset, len, (_enclosing.Flags2 & SmbConstants.Flags2Unicode) != 0);
- if (_nodeOffset > 0)
- {
- Node = _enclosing.ReadString(buffer, start + _nodeOffset, len, (_enclosing.Flags2 & SmbConstants.Flags2Unicode) != 0);
- }
- }
- else
- {
- if (_version == 1)
- {
- Node = _enclosing.ReadString(buffer, bufferIndex, len, (_enclosing
- .Flags2 & SmbConstants.Flags2Unicode) != 0);
- }
- }
- return _size;
- }
-
- public override string ToString()
- {
- return "Referral[" + "version=" + _version + ",size=" + _size
- + ",serverType=" + _serverType + ",flags=" + _flags + ",proximity=" + _proximity + ",ttl=" + Ttl + ",pathOffset=" + _pathOffset + ",altPathOffset="
- + _altPathOffset + ",nodeOffset=" + _nodeOffset + ",path=" + Path
- + ",altPath=" + _altPath + ",node=" + Node + "]";
- }
-
- internal Referral(Trans2GetDfsReferralResponse enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly Trans2GetDfsReferralResponse _enclosing;
- }
-
- internal int PathConsumed;
-
- internal int NumReferrals;
-
- internal int flags;
-
- internal Referral[] Referrals;
-
- public Trans2GetDfsReferralResponse()
- {
- SubCommand = Smb.SmbComTransaction.Trans2GetDfsReferral;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- int start = bufferIndex;
- PathConsumed = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- if ((Flags2 & SmbConstants.Flags2Unicode) != 0)
- {
- PathConsumed /= 2;
- }
- NumReferrals = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- flags = ReadInt2(buffer, bufferIndex);
- bufferIndex += 4;
- Referrals = new Referral[NumReferrals];
- for (int ri = 0; ri < NumReferrals; ri++)
- {
- Referrals[ri] = new Referral(this);
- bufferIndex += Referrals[ri].ReadWireFormat(buffer, bufferIndex, len);
- }
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "Trans2GetDfsReferralResponse[" + base.ToString() + ",pathConsumed="
- + PathConsumed + ",numReferrals=" + NumReferrals + ",flags=" + flags + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs
deleted file mode 100644
index 27b350e53..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2QueryFsInformation : SmbComTransaction
- {
- private int _informationLevel;
-
- internal Trans2QueryFsInformation(int informationLevel)
- {
- Command = SmbComTransaction2;
- SubCommand = Trans2QueryFsInformation;
- this._informationLevel = informationLevel;
- TotalParameterCount = 2;
- TotalDataCount = 0;
- MaxParameterCount = 0;
- MaxDataCount = 800;
- MaxSetupCount = 0;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_informationLevel, dst, dstIndex);
- dstIndex += 2;
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2QueryFSInformation[" + base.ToString() + ",informationLevel=0x"
- + Hexdump.ToHexString(_informationLevel, 3) + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs
deleted file mode 100644
index 2253e7b6f..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs
+++ /dev/null
@@ -1,192 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class Trans2QueryFsInformationResponse : SmbComTransactionResponse
- {
- internal const int SMB_INFO_ALLOCATION = 1;
-
- internal const int SmbQueryFsSizeInfo = unchecked(0x103);
-
- internal const int SmbFsFullSizeInformation = 1007;
-
- internal class SmbInfoAllocation : IAllocInfo
- {
- internal long Alloc;
-
- internal long Free;
-
- internal int SectPerAlloc;
-
- internal int BytesPerSect;
-
- // information levels
- // Also handles SmbQueryFSSizeInfo
- public virtual long GetCapacity()
- {
- return Alloc * SectPerAlloc * BytesPerSect;
- }
-
- public virtual long GetFree()
- {
- return Free * SectPerAlloc * BytesPerSect;
- }
-
- public override string ToString()
- {
- return "SmbInfoAllocation[" + "alloc=" + Alloc + ",free=" + Free + ",sectPerAlloc=" + SectPerAlloc + ",bytesPerSect=" + BytesPerSect
- + "]";
- }
-
- internal SmbInfoAllocation(Trans2QueryFsInformationResponse enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly Trans2QueryFsInformationResponse _enclosing;
- }
-
- private int _informationLevel;
-
- internal IAllocInfo Info;
-
- internal Trans2QueryFsInformationResponse(int informationLevel)
- {
- this._informationLevel = informationLevel;
- Command = SmbComTransaction2;
- SubCommand = Smb.SmbComTransaction.Trans2QueryFsInformation;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- switch (_informationLevel)
- {
- case SMB_INFO_ALLOCATION:
- {
- return ReadSmbInfoAllocationWireFormat(buffer, bufferIndex);
- }
-
- case SmbQueryFsSizeInfo:
- {
- return ReadSmbQueryFsSizeInfoWireFormat(buffer, bufferIndex);
- }
-
- case SmbFsFullSizeInformation:
- {
- return ReadFsFullSizeInformationWireFormat(buffer, bufferIndex);
- }
-
- default:
- {
- return 0;
- }
- }
- }
-
- internal virtual int ReadSmbInfoAllocationWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- SmbInfoAllocation info = new SmbInfoAllocation
- (this);
- bufferIndex += 4;
- // skip idFileSystem
- info.SectPerAlloc = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.Alloc = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.Free = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.BytesPerSect = ReadInt2(buffer, bufferIndex);
- bufferIndex += 4;
- this.Info = info;
- return bufferIndex - start;
- }
-
- internal virtual int ReadSmbQueryFsSizeInfoWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- SmbInfoAllocation info = new SmbInfoAllocation
- (this);
- info.Alloc = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- info.Free = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- info.SectPerAlloc = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.BytesPerSect = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- this.Info = info;
- return bufferIndex - start;
- }
-
- internal virtual int ReadFsFullSizeInformationWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- SmbInfoAllocation info = new SmbInfoAllocation
- (this);
- // Read total allocation units.
- info.Alloc = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- // read caller available allocation units
- info.Free = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- // skip actual free units
- bufferIndex += 8;
- info.SectPerAlloc = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.BytesPerSect = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- this.Info = info;
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "Trans2QueryFSInformationResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs
deleted file mode 100644
index b3db64790..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2QueryPathInformation : SmbComTransaction
- {
- private int _informationLevel;
-
- internal Trans2QueryPathInformation(string filename, int informationLevel)
- {
- Path = filename;
- this._informationLevel = informationLevel;
- Command = SmbComTransaction2;
- SubCommand = Trans2QueryPathInformation;
- TotalDataCount = 0;
- MaxParameterCount = 2;
- MaxDataCount = 40;
- MaxSetupCount = unchecked(unchecked(0x00));
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_informationLevel, dst, dstIndex);
- dstIndex += 2;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dstIndex += WriteString(Path, dst, dstIndex);
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2QueryPathInformation[" + base.ToString() + ",informationLevel=0x"
- + Hexdump.ToHexString(_informationLevel, 3) + ",filename=" + Path + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs
deleted file mode 100644
index 50650df62..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs
+++ /dev/null
@@ -1,227 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class Trans2QueryPathInformationResponse : SmbComTransactionResponse
- {
- internal const int SMB_QUERY_FILE_BASIC_INFO = unchecked(0x101);
-
- internal const int SMB_QUERY_FILE_STANDARD_INFO = unchecked(0x102);
-
- internal class SmbQueryFileBasicInfo : IInfo
- {
- internal long CreateTime;
-
- internal long LastAccessTime;
-
- internal long LastWriteTime;
-
- internal long ChangeTime;
-
- internal int Attributes;
-
- // information levels
- public virtual int GetAttributes()
- {
- return Attributes;
- }
-
- public virtual long GetCreateTime()
- {
- return CreateTime;
- }
-
- public virtual long GetLastWriteTime()
- {
- return LastWriteTime;
- }
-
- public virtual long GetSize()
- {
- return 0L;
- }
-
- public override string ToString()
- {
- return "SmbQueryFileBasicInfo[" + "createTime=" + Extensions.CreateDate
- (CreateTime) + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime
- ) + ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",changeTime="
- + Extensions.CreateDate(ChangeTime) + ",attributes=0x" + Hexdump.ToHexString
- (Attributes, 4) + "]";
- }
-
- internal SmbQueryFileBasicInfo(Trans2QueryPathInformationResponse enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly Trans2QueryPathInformationResponse _enclosing;
- }
-
- internal class SmbQueryFileStandardInfo : IInfo
- {
- internal long AllocationSize;
-
- internal long EndOfFile;
-
- internal int NumberOfLinks;
-
- internal bool DeletePending;
-
- internal bool Directory;
-
- public virtual int GetAttributes()
- {
- return 0;
- }
-
- public virtual long GetCreateTime()
- {
- return 0L;
- }
-
- public virtual long GetLastWriteTime()
- {
- return 0L;
- }
-
- public virtual long GetSize()
- {
- return EndOfFile;
- }
-
- public override string ToString()
- {
- return "SmbQueryInfoStandard[" + "allocationSize=" + AllocationSize
- + ",endOfFile=" + EndOfFile + ",numberOfLinks=" + NumberOfLinks + ",deletePending="
- + DeletePending + ",directory=" + Directory + "]";
- }
-
- internal SmbQueryFileStandardInfo(Trans2QueryPathInformationResponse enclosing)
- {
- this._enclosing = enclosing;
- }
-
- private readonly Trans2QueryPathInformationResponse _enclosing;
- }
-
- private int _informationLevel;
-
- internal IInfo Info;
-
- internal Trans2QueryPathInformationResponse(int informationLevel)
- {
- this._informationLevel = informationLevel;
- SubCommand = Smb.SmbComTransaction.Trans2QueryPathInformation;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- // observed two zero bytes here with at least win98
- return 2;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- switch (_informationLevel)
- {
- case SMB_QUERY_FILE_BASIC_INFO:
- {
- return ReadSmbQueryFileBasicInfoWireFormat(buffer, bufferIndex);
- }
-
- case SMB_QUERY_FILE_STANDARD_INFO:
- {
- return ReadSmbQueryFileStandardInfoWireFormat(buffer, bufferIndex);
- }
-
- default:
- {
- return 0;
- }
- }
- }
-
- internal virtual int ReadSmbQueryFileStandardInfoWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- SmbQueryFileStandardInfo info = new SmbQueryFileStandardInfo
- (this);
- info.AllocationSize = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- info.EndOfFile = ReadInt8(buffer, bufferIndex);
- bufferIndex += 8;
- info.NumberOfLinks = ReadInt4(buffer, bufferIndex);
- bufferIndex += 4;
- info.DeletePending = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
- info.Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
- this.Info = info;
- return bufferIndex - start;
- }
-
- internal virtual int ReadSmbQueryFileBasicInfoWireFormat(byte[] buffer, int bufferIndex
- )
- {
- int start = bufferIndex;
- SmbQueryFileBasicInfo info = new SmbQueryFileBasicInfo
- (this);
- info.CreateTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- info.LastAccessTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- info.LastWriteTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- info.ChangeTime = ReadTime(buffer, bufferIndex);
- bufferIndex += 8;
- info.Attributes = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- this.Info = info;
- return bufferIndex - start;
- }
-
- public override string ToString()
- {
- return "Trans2QueryPathInformationResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs
deleted file mode 100644
index 289cab866..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class Trans2SetFileInformation : SmbComTransaction
- {
- internal const int SmbFileBasicInfo = unchecked(0x101);
-
- private int _fid;
-
- private int _attributes;
-
- private long _createTime;
-
- private long _lastWriteTime;
-
- internal Trans2SetFileInformation(int fid, int attributes, long createTime, long
- lastWriteTime)
- {
- this._fid = fid;
- this._attributes = attributes;
- this._createTime = createTime;
- this._lastWriteTime = lastWriteTime;
- Command = SmbComTransaction2;
- SubCommand = Trans2SetFileInformation;
- MaxParameterCount = 6;
- MaxDataCount = 0;
- MaxSetupCount = unchecked(unchecked(0x00));
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 2;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteInt2(_fid, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(SmbFileBasicInfo, dst, dstIndex);
- dstIndex += 2;
- WriteInt2(0, dst, dstIndex);
- dstIndex += 2;
- return dstIndex - start;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- int start = dstIndex;
- WriteTime(_createTime, dst, dstIndex);
- dstIndex += 8;
- WriteInt8(0L, dst, dstIndex);
- dstIndex += 8;
- WriteTime(_lastWriteTime, dst, dstIndex);
- dstIndex += 8;
- WriteInt8(0L, dst, dstIndex);
- dstIndex += 8;
- WriteInt2(unchecked(0x80) | _attributes, dst, dstIndex);
- dstIndex += 2;
- WriteInt8(0L, dst, dstIndex);
- dstIndex += 6;
- return dstIndex - start;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2SetFileInformation[" + base.ToString() + ",fid=" + _fid +
- "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs
deleted file mode 100644
index b21f356b4..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class Trans2SetFileInformationResponse : SmbComTransactionResponse
- {
- public Trans2SetFileInformationResponse()
- {
- SubCommand = Smb.SmbComTransaction.Trans2SetFileInformation;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "Trans2SetFileInformationResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs
deleted file mode 100644
index 404af0aaa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal class TransCallNamedPipe : SmbComTransaction
- {
- private byte[] _pipeData;
-
- private int _pipeDataOff;
-
- private int _pipeDataLen;
-
- internal TransCallNamedPipe(string pipeName, byte[] data, int off, int len)
- {
- Name = pipeName;
- _pipeData = data;
- _pipeDataOff = off;
- _pipeDataLen = len;
- Command = SmbComTransaction;
- SubCommand = TransCallNamedPipe;
- Timeout = unchecked((int)(0xFFFFFFFF));
- MaxParameterCount = 0;
- MaxDataCount = unchecked(0xFFFF);
- MaxSetupCount = unchecked(unchecked(0x00));
- SetupCount = 2;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // this says "Transaction priority" in netmon
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // no FID
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 4;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- if ((dst.Length - dstIndex) < _pipeDataLen)
- {
- if (Log.Level >= 3)
- {
- Log.WriteLine("TransCallNamedPipe data too long for buffer");
- }
- return 0;
- }
- Array.Copy(_pipeData, _pipeDataOff, dst, dstIndex, _pipeDataLen);
- return _pipeDataLen;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransCallNamedPipe[" + base.ToString() + ",pipeName=" + Name +
- "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs
deleted file mode 100644
index b86cc7fdb..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class TransCallNamedPipeResponse : SmbComTransactionResponse
- {
- private SmbNamedPipe _pipe;
-
- internal TransCallNamedPipeResponse(SmbNamedPipe pipe)
- {
- this._pipe = pipe;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- if (_pipe.PipeIn != null)
- {
- TransactNamedPipeInputStream @in = (TransactNamedPipeInputStream)_pipe.PipeIn;
- lock (@in.Lock)
- {
- @in.Receive(buffer, bufferIndex, len);
- Runtime.Notify(@in.Lock);
- }
- }
- return len;
- }
-
- public override string ToString()
- {
- return "TransCallNamedPipeResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs
deleted file mode 100644
index 9b80bbe1e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class TransPeekNamedPipe : SmbComTransaction
- {
- private int _fid;
-
- internal TransPeekNamedPipe(string pipeName, int fid)
- {
- Name = pipeName;
- this._fid = fid;
- Command = SmbComTransaction;
- SubCommand = TransPeekNamedPipe;
- Timeout = unchecked((int)(0xFFFFFFFF));
- MaxParameterCount = 6;
- MaxDataCount = 1;
- MaxSetupCount = unchecked(unchecked(0x00));
- SetupCount = 2;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // this says "Transaction priority" in netmon
- WriteInt2(_fid, dst, dstIndex);
- return 4;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransPeekNamedPipe[" + base.ToString() + ",pipeName=" + Name +
- "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs
deleted file mode 100644
index 6bcf2d07e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class TransPeekNamedPipeResponse : SmbComTransactionResponse
- {
- private SmbNamedPipe _pipe;
-
- private int _head;
-
- internal const int StatusDisconnected = 1;
-
- internal const int StatusListening = 2;
-
- internal const int StatusConnectionOk = 3;
-
- internal const int StatusServerEndClosed = 4;
-
- internal int status;
-
- internal int Available;
-
- internal TransPeekNamedPipeResponse(SmbNamedPipe pipe)
- {
- this._pipe = pipe;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- Available = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- _head = ReadInt2(buffer, bufferIndex);
- bufferIndex += 2;
- status = ReadInt2(buffer, bufferIndex);
- return 6;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransPeekNamedPipeResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs
deleted file mode 100644
index 1b6ec9cca..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Smb
-{
- internal class TransTransactNamedPipe : SmbComTransaction
- {
- private byte[] _pipeData;
-
- private int _pipeFid;
-
- private int _pipeDataOff;
-
- private int _pipeDataLen;
-
- internal TransTransactNamedPipe(int fid, byte[] data, int off, int len)
- {
- _pipeFid = fid;
- _pipeData = data;
- _pipeDataOff = off;
- _pipeDataLen = len;
- Command = SmbComTransaction;
- SubCommand = TransTransactNamedPipe;
- MaxParameterCount = 0;
- MaxDataCount = unchecked(0xFFFF);
- MaxSetupCount = unchecked(unchecked(0x00));
- SetupCount = 2;
- Name = "\\PIPE\\";
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- WriteInt2(_pipeFid, dst, dstIndex);
- dstIndex += 2;
- return 4;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- if ((dst.Length - dstIndex) < _pipeDataLen)
- {
- if (Log.Level >= 3)
- {
- Log.WriteLine("TransTransactNamedPipe data too long for buffer");
- }
- return 0;
- }
- Array.Copy(_pipeData, _pipeDataOff, dst, dstIndex, _pipeDataLen);
- return _pipeDataLen;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransTransactNamedPipe[" + base.ToString() + ",pipeFid=" + _pipeFid
- + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs
deleted file mode 100644
index b8d14781c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class TransTransactNamedPipeResponse : SmbComTransactionResponse
- {
- private SmbNamedPipe _pipe;
-
- internal TransTransactNamedPipeResponse(SmbNamedPipe pipe)
- {
- this._pipe = pipe;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- if (_pipe.PipeIn != null)
- {
- TransactNamedPipeInputStream @in = (TransactNamedPipeInputStream)_pipe.PipeIn;
- lock (@in.Lock)
- {
- @in.Receive(buffer, bufferIndex, len);
- Runtime.Notify(@in.Lock);
- }
- }
- return len;
- }
-
- public override string ToString()
- {
- return "TransTransactNamedPipeResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs
deleted file mode 100644
index a184665aa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class TransWaitNamedPipe : SmbComTransaction
- {
- internal TransWaitNamedPipe(string pipeName)
- {
- Name = pipeName;
- Command = SmbComTransaction;
- SubCommand = TransWaitNamedPipe;
- Timeout = unchecked((int)(0xFFFFFFFF));
- MaxParameterCount = 0;
- MaxDataCount = 0;
- MaxSetupCount = unchecked(unchecked(0x00));
- SetupCount = 2;
- }
-
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- dst[dstIndex++] = SubCommand;
- dst[dstIndex++] = unchecked(unchecked(0x00));
- dst[dstIndex++] = unchecked(unchecked(0x00));
- // no FID
- dst[dstIndex++] = unchecked(unchecked(0x00));
- return 4;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransWaitNamedPipe[" + base.ToString() + ",pipeName=" + Name +
- "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs
deleted file mode 100644
index a62a82ec7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class TransWaitNamedPipeResponse : SmbComTransactionResponse
- {
- // not much to this one is there :~)
- internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
- {
- return 0;
- }
-
- internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
- )
- {
- return 0;
- }
-
- internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
- len)
- {
- return 0;
- }
-
- internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
- {
- return 0;
- }
-
- public override string ToString()
- {
- return "TransWaitNamedPipeResponse[" + base.ToString() + "]";
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs
deleted file mode 100644
index 46d418582..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs
+++ /dev/null
@@ -1,180 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Smb
-{
- internal class TransactNamedPipeInputStream : SmbFileInputStream
- {
- private const int InitPipeSize = 4096;
-
- private byte[] _pipeBuf = new byte[InitPipeSize];
-
- private int _begIdx;
-
- private int _nxtIdx;
-
- private int _used;
-
- private bool _dcePipe;
-
- internal object Lock;
-
- /// <exception cref="SharpCifs.Smb.SmbException"></exception>
- /// <exception cref="System.UriFormatException"></exception>
- /// <exception cref="UnknownHostException"></exception>
- internal TransactNamedPipeInputStream(SmbNamedPipe pipe) : base(pipe, (pipe.PipeType
- & unchecked((int)(0xFFFF00FF))) | SmbFile.OExcl)
- {
- _dcePipe = (pipe.PipeType & SmbNamedPipe.PipeTypeDceTransact) != SmbNamedPipe
- .PipeTypeDceTransact;
- Lock = new object();
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override int Read()
- {
- int result = -1;
- lock (Lock)
- {
- try
- {
- while (_used == 0)
- {
- Runtime.Wait(Lock);
- }
- }
- catch (Exception ie)
- {
- throw new IOException(ie.Message);
- }
- result = _pipeBuf[_begIdx] & unchecked(0xFF);
- _begIdx = (_begIdx + 1) % _pipeBuf.Length;
- }
- return result;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override int Read(byte[] b)
- {
- return Read(b, 0, b.Length);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override int Read(byte[] b, int off, int len)
- {
- int result = -1;
- int i;
- if (len <= 0)
- {
- return 0;
- }
- lock (Lock)
- {
- try
- {
- while (_used == 0)
- {
- Runtime.Wait(Lock);
- }
- }
- catch (Exception ie)
- {
- throw new IOException(ie.Message);
- }
- i = _pipeBuf.Length - _begIdx;
- result = len > _used ? _used : len;
- if (_used > i && result > i)
- {
- Array.Copy(_pipeBuf, _begIdx, b, off, i);
- off += i;
- Array.Copy(_pipeBuf, 0, b, off, result - i);
- }
- else
- {
- Array.Copy(_pipeBuf, _begIdx, b, off, result);
- }
- _used -= result;
- _begIdx = (_begIdx + result) % _pipeBuf.Length;
- }
- return result;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override int Available()
- {
- if (File.Log.Level >= 3)
- {
- File.Log.WriteLine("Named Pipe available() does not apply to TRANSACT Named Pipes"
- );
- }
- return 0;
- }
-
- internal virtual int Receive(byte[] b, int off, int len)
- {
- int i;
- if (len > (_pipeBuf.Length - _used))
- {
- byte[] tmp;
- int newSize;
- newSize = _pipeBuf.Length * 2;
- if (len > (newSize - _used))
- {
- newSize = len + _used;
- }
- tmp = _pipeBuf;
- _pipeBuf = new byte[newSize];
- i = tmp.Length - _begIdx;
- if (_used > i)
- {
- Array.Copy(tmp, _begIdx, _pipeBuf, 0, i);
- Array.Copy(tmp, 0, _pipeBuf, i, _used - i);
- }
- else
- {
- Array.Copy(tmp, _begIdx, _pipeBuf, 0, _used);
- }
- _begIdx = 0;
- _nxtIdx = _used;
- tmp = null;
- }
- i = _pipeBuf.Length - _nxtIdx;
- if (len > i)
- {
- Array.Copy(b, off, _pipeBuf, _nxtIdx, i);
- off += i;
- Array.Copy(b, off, _pipeBuf, 0, len - i);
- }
- else
- {
- Array.Copy(b, off, _pipeBuf, _nxtIdx, len);
- }
- _nxtIdx = (_nxtIdx + len) % _pipeBuf.Length;
- _used += len;
- return len;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual int Dce_read(byte[] b, int off, int len)
- {
- return base.Read(b, off, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs
deleted file mode 100644
index d3e8d3e1a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- internal class TransactNamedPipeOutputStream : SmbFileOutputStream
- {
- private string _path;
-
- private SmbNamedPipe _pipe;
-
- private byte[] _tmp = new byte[1];
-
- private bool _dcePipe;
-
- /// <exception cref="System.IO.IOException"></exception>
- internal TransactNamedPipeOutputStream(SmbNamedPipe pipe) : base(pipe, false, (pipe
- .PipeType & unchecked((int)(0xFFFF00FF))) | SmbFile.OExcl)
- {
- this._pipe = pipe;
- _dcePipe = (pipe.PipeType & SmbNamedPipe.PipeTypeDceTransact) == SmbNamedPipe
- .PipeTypeDceTransact;
- _path = pipe.Unc;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override void Close()
- {
- _pipe.Close();
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override void Write(int b)
- {
- _tmp[0] = unchecked((byte)b);
- Write(_tmp, 0, 1);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override void Write(byte[] b)
- {
- Write(b, 0, b.Length);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public override void Write(byte[] b, int off, int len)
- {
- if (len < 0)
- {
- len = 0;
- }
- if ((_pipe.PipeType & SmbNamedPipe.PipeTypeCall) == SmbNamedPipe.PipeTypeCall)
- {
- _pipe.Send(new TransWaitNamedPipe(_path), new TransWaitNamedPipeResponse());
- _pipe.Send(new TransCallNamedPipe(_path, b, off, len), new TransCallNamedPipeResponse
- (_pipe));
- }
- else
- {
- if ((_pipe.PipeType & SmbNamedPipe.PipeTypeTransact) == SmbNamedPipe.PipeTypeTransact)
- {
- EnsureOpen();
- TransTransactNamedPipe req = new TransTransactNamedPipe(_pipe.Fid, b, off, len);
- if (_dcePipe)
- {
- req.MaxDataCount = 1024;
- }
- _pipe.Send(req, new TransTransactNamedPipeResponse(_pipe));
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs
deleted file mode 100644
index daecc5407..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Smb
-{
- public static class WinError
- {
- public static int ErrorSuccess = 0;
-
- public static int ErrorAccessDenied = 5;
-
- public static int ErrorReqNotAccep = 71;
-
- public static int ErrorBadPipe = 230;
-
- public static int ErrorPipeBusy = 231;
-
- public static int ErrorNoData = 232;
-
- public static int ErrorPipeNotConnected = 233;
-
- public static int ErrorMoreData = 234;
-
- public static int ErrorNoBrowserServersFound = 6118;
-
- public static int[] WinerrCodes = { ErrorSuccess, ErrorAccessDenied,
- ErrorReqNotAccep, ErrorBadPipe, ErrorPipeBusy, ErrorNoData, ErrorPipeNotConnected
- , ErrorMoreData, ErrorNoBrowserServersFound };
-
- public static string[] WinerrMessages = { "The operation completed successfully."
- , "Access is denied.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."
- , "The pipe state is invalid.", "All pipe instances are busy.", "The pipe is being closed."
- , "No process is on the other end of the pipe.", "More data is available.", "The list of servers for this workgroup is not currently available."
- };
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs b/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs
deleted file mode 100644
index 816fbe781..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs
+++ /dev/null
@@ -1,591 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using System.Linq;
-using System.Net;
-using SharpCifs.Netbios;
-using SharpCifs.Util;
-using SharpCifs.Util.Sharpen;
-using Extensions = SharpCifs.Util.Sharpen.Extensions;
-
-namespace SharpCifs
-{
- /// <summary>
- /// <p>Under normal conditions it is not necessary to use
- /// this class to use jCIFS properly.
- /// </summary>
- /// <remarks>
- /// <p>Under normal conditions it is not necessary to use
- /// this class to use jCIFS properly. Name resolusion is
- /// handled internally to the <code>jcifs.smb</code> package.
- /// <p>
- /// This class is a wrapper for both
- /// <see cref="Jcifs.Netbios.NbtAddress">Jcifs.Netbios.NbtAddress</see>
- /// and
- /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
- /// . The name resolution mechanisms
- /// used will systematically query all available configured resolution
- /// services including WINS, broadcasts, DNS, and LMHOSTS. See
- /// <a href="../../resolver.html">Setting Name Resolution Properties</a>
- /// and the <code>jcifs.resolveOrder</code> property. Changing
- /// jCIFS name resolution properties can greatly affect the behavior of
- /// the client and may be necessary for proper operation.
- /// <p>
- /// This class should be used in favor of <tt>InetAddress</tt> to resolve
- /// hostnames on LANs and WANs that support a mixture of NetBIOS/WINS and
- /// DNS resolvable hosts.
- /// </remarks>
- public class UniAddress
- {
- private const int ResolverWins = 0;
-
- private const int ResolverBcast = 1;
-
- private const int ResolverDns = 2;
-
- private const int ResolverLmhosts = 3;
-
- private static int[] _resolveOrder;
-
- private static IPAddress _baddr;
-
- private static LogStream _log = LogStream.GetInstance();
-
- static UniAddress()
- {
- string ro = Config.GetProperty("jcifs.resolveOrder");
- IPAddress nbns = NbtAddress.GetWinsAddress();
- try
- {
- _baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName
- ("255.255.255.255"));
- }
- catch (UnknownHostException)
- {
- }
- if (string.IsNullOrEmpty(ro))
- {
- if (nbns == null)
- {
- _resolveOrder = new int[3];
- _resolveOrder[0] = ResolverLmhosts;
- _resolveOrder[1] = ResolverDns;
- _resolveOrder[2] = ResolverBcast;
- }
- else
- {
- _resolveOrder = new int[4];
- _resolveOrder[0] = ResolverLmhosts;
- _resolveOrder[1] = ResolverWins;
- _resolveOrder[2] = ResolverDns;
- _resolveOrder[3] = ResolverBcast;
- }
- }
- else
- {
- int[] tmp = new int[4];
- StringTokenizer st = new StringTokenizer(ro, ",");
- int i = 0;
- while (st.HasMoreTokens())
- {
- string s = st.NextToken().Trim();
- if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
- {
- tmp[i++] = ResolverLmhosts;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "WINS"))
- {
- if (nbns == null)
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("UniAddress resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
- );
- }
- continue;
- }
- tmp[i++] = ResolverWins;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "BCAST"))
- {
- tmp[i++] = ResolverBcast;
- }
- else
- {
- if (Runtime.EqualsIgnoreCase(s, "DNS"))
- {
- tmp[i++] = ResolverDns;
- }
- else
- {
- if (_log.Level > 1)
- {
- _log.WriteLine("unknown resolver method: " + s);
- }
- }
- }
- }
- }
- }
- _resolveOrder = new int[i];
- Array.Copy(tmp, 0, _resolveOrder, 0, i);
- }
- }
-
- internal class Sem
- {
- internal Sem(int count)
- {
- this.Count = count;
- }
-
- internal int Count;
- }
-
- internal class QueryThread : Thread
- {
- internal Sem Sem;
-
- internal string Host;
-
- internal string Scope;
-
- internal int Type;
-
- internal NbtAddress[] Ans;
-
- internal IPAddress Svr;
-
- internal UnknownHostException Uhe;
-
- internal QueryThread(Sem sem, string host, int type, string scope, IPAddress
- svr) : base("JCIFS-QueryThread: " + host)
- {
- this.Sem = sem;
- this.Host = host;
- this.Type = type;
- this.Scope = scope;
- this.Svr = svr;
- }
-
- public override void Run()
- {
- try
- {
- //Ans = new [] { NbtAddress.GetByName(Host, Type, Scope, Svr) };
- Ans = NbtAddress.GetAllByName(Host, Type, Scope, Svr);
- }
- catch (UnknownHostException uhe)
- {
- this.Uhe = uhe;
- }
- catch (Exception ex)
- {
- Uhe = new UnknownHostException(ex.Message);
- }
- finally
- {
- lock (Sem)
- {
- Sem.Count--;
- Runtime.Notify(Sem);
- }
- }
- }
- }
-
- /// <exception cref="UnknownHostException"></exception>
- internal static NbtAddress[] LookupServerOrWorkgroup(string name, IPAddress svr)
- {
- Sem sem = new Sem(2);
- int type = NbtAddress.IsWins(svr) ? unchecked(0x1b) : unchecked(0x1d);
- QueryThread q1X = new QueryThread(sem, name, type, null, svr
- );
- QueryThread q20 = new QueryThread(sem, name, unchecked(0x20), null, svr);
- q1X.SetDaemon(true);
- q20.SetDaemon(true);
- try
- {
- lock (sem)
- {
- q1X.Start();
- q20.Start();
- while (sem.Count > 0 && q1X.Ans == null && q20.Ans == null)
- {
- Runtime.Wait(sem);
- }
- }
- }
- catch (Exception)
- {
- throw new UnknownHostException(name);
- }
- if (q1X.Ans != null)
- {
- return q1X.Ans;
- }
- if (q20.Ans != null)
- {
- return q20.Ans;
- }
- throw q1X.Uhe;
- }
-
- /// <summary>Determines the address of a host given it's host name.</summary>
- /// <remarks>
- /// Determines the address of a host given it's host name. The name can be a
- /// machine name like "jcifs.samba.org", or an IP address like "192.168.1.15".
- /// </remarks>
- /// <param name="hostname">NetBIOS or DNS hostname to resolve</param>
- /// <exception cref="UnknownHostException">if there is an error resolving the name
- /// </exception>
- public static UniAddress GetByName(string hostname)
- {
- return GetByName(hostname, false);
- }
-
- internal static bool IsDotQuadIp(string hostname)
- {
- if (char.IsDigit(hostname[0]))
- {
- int i;
- int len;
- int dots;
- char[] data;
- i = dots = 0;
- len = hostname.Length;
- data = hostname.ToCharArray();
- while (i < len && char.IsDigit(data[i++]))
- {
- if (i == len && dots == 3)
- {
- // probably an IP address
- return true;
- }
- if (i < len && data[i] == '.')
- {
- dots++;
- i++;
- }
- }
- }
- return false;
- }
-
- internal static bool IsAllDigits(string hostname)
- {
- for (int i = 0; i < hostname.Length; i++)
- {
- if (char.IsDigit(hostname[i]) == false)
- {
- return false;
- }
- }
- return true;
- }
-
- /// <summary>Lookup <tt>hostname</tt> and return it's <tt>UniAddress</tt>.</summary>
- /// <remarks>
- /// Lookup <tt>hostname</tt> and return it's <tt>UniAddress</tt>. If the
- /// <tt>possibleNTDomainOrWorkgroup</tt> parameter is <tt>true</tt> an
- /// addtional name query will be performed to locate a master browser.
- /// </remarks>
- /// <exception cref="UnknownHostException"></exception>
- public static UniAddress GetByName(string hostname, bool possibleNtDomainOrWorkgroup
- )
- {
- UniAddress[] addrs = GetAllByName(hostname, possibleNtDomainOrWorkgroup
- );
- return addrs[0];
- }
-
- /// <exception cref="UnknownHostException"></exception>
- public static UniAddress[] GetAllByName(string hostname, bool possibleNtDomainOrWorkgroup
- )
- {
- object addr;
- int i;
- if (string.IsNullOrEmpty(hostname))
- {
- throw new UnknownHostException();
- }
- if (IsDotQuadIp(hostname))
- {
- UniAddress[] addrs = new UniAddress[1];
- addrs[0] = new UniAddress(NbtAddress.GetByName(hostname));
- return addrs;
- }
- for (i = 0; i < _resolveOrder.Length; i++)
- {
- try
- {
- switch (_resolveOrder[i])
- {
- case ResolverLmhosts:
- {
- if ((addr = Lmhosts.GetByName(hostname)) == null)
- {
- continue;
- }
- break;
- }
-
- case ResolverWins:
- {
- if (hostname == NbtAddress.MasterBrowserName || hostname.Length > 15)
- {
- // invalid netbios name
- continue;
- }
- if (possibleNtDomainOrWorkgroup)
- {
- addr = LookupServerOrWorkgroup(hostname, NbtAddress.GetWinsAddress());
- }
- else
- {
- addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, NbtAddress.GetWinsAddress
- ());
- }
- break;
- }
-
- case ResolverBcast:
- {
- if (hostname.Length > 15)
- {
- // invalid netbios name
- continue;
- }
-
- try
- {
- if (possibleNtDomainOrWorkgroup)
- {
- NbtAddress[] iaddrs = LookupServerOrWorkgroup(hostname, _baddr);
-
- UniAddress[] addrs = new UniAddress[iaddrs.Length];
- for (int ii = 0; ii < iaddrs.Length; ii++)
- {
- addrs[ii] = new UniAddress(iaddrs[ii]);
- }
- return addrs;
-
- }
- else
- {
- addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, _baddr);
- }
-
- }
- catch (Exception ex)
- {
- if (i == _resolveOrder.Length - 1)
- {
- throw ex;
- }
- else
- {
- continue;
- }
- }
- break;
- }
-
- case ResolverDns:
- {
- if (IsAllDigits(hostname))
- {
- throw new UnknownHostException(hostname);
- }
-
- IPAddress[] iaddrs = Extensions.GetAddressesByName(hostname);
-
- if (iaddrs == null || iaddrs.Length == 0)
- {
- continue;
- }
-
- return iaddrs.Select(iaddr => new UniAddress(iaddr)).ToArray();
- }
-
- default:
- {
- // Success
- throw new UnknownHostException(hostname);
- }
- }
- UniAddress[] addrs1 = new UniAddress[1];
- addrs1[0] = new UniAddress(addr);
- return addrs1;
- }
- catch (IOException)
- {
- }
- }
- // Success
- // Failure
- throw new UnknownHostException(hostname);
- }
-
- internal object Addr;
-
- internal string CalledName;
-
- /// <summary>
- /// Create a <tt>UniAddress</tt> by wrapping an <tt>InetAddress</tt> or
- /// <tt>NbtAddress</tt>.
- /// </summary>
- /// <remarks>
- /// Create a <tt>UniAddress</tt> by wrapping an <tt>InetAddress</tt> or
- /// <tt>NbtAddress</tt>.
- /// </remarks>
- public UniAddress(object addr)
- {
- if (addr == null)
- {
- throw new ArgumentException();
- }
- this.Addr = addr;
- }
-
- /// <summary>Return the IP address of this address as a 32 bit integer.</summary>
- /// <remarks>Return the IP address of this address as a 32 bit integer.</remarks>
- public override int GetHashCode()
- {
- return Addr.GetHashCode();
- }
-
- /// <summary>Compare two addresses for equality.</summary>
- /// <remarks>
- /// Compare two addresses for equality. Two <tt>UniAddress</tt>s are equal
- /// if they are both <tt>UniAddress</tt>' and refer to the same IP address.
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is UniAddress && Addr.Equals(((UniAddress)obj).Addr);
- }
-
- /// <summary>Guess first called name to try for session establishment.</summary>
- /// <remarks>
- /// Guess first called name to try for session establishment. This
- /// method is used exclusively by the <tt>jcifs.smb</tt> package.
- /// </remarks>
- public virtual string FirstCalledName()
- {
- if (Addr is NbtAddress)
- {
- return ((NbtAddress)Addr).FirstCalledName();
- }
- CalledName = ((IPAddress) Addr).GetHostAddress();
- if (IsDotQuadIp(CalledName))
- {
- CalledName = NbtAddress.SmbserverName;
- }
- else
- {
- int i = CalledName.IndexOf('.');
- if (i > 1 && i < 15)
- {
- CalledName = Runtime.Substring(CalledName, 0, i).ToUpper();
- }
- else
- {
- if (CalledName.Length > 15)
- {
- CalledName = NbtAddress.SmbserverName;
- }
- else
- {
- CalledName = CalledName.ToUpper();
- }
- }
- }
- return CalledName;
- }
-
- /// <summary>Guess next called name to try for session establishment.</summary>
- /// <remarks>
- /// Guess next called name to try for session establishment. This
- /// method is used exclusively by the <tt>jcifs.smb</tt> package.
- /// </remarks>
- public virtual string NextCalledName()
- {
- if (Addr is NbtAddress)
- {
- return ((NbtAddress)Addr).NextCalledName();
- }
- if (CalledName != NbtAddress.SmbserverName)
- {
- CalledName = NbtAddress.SmbserverName;
- return CalledName;
- }
- return null;
- }
-
- /// <summary>Return the underlying <tt>NbtAddress</tt> or <tt>InetAddress</tt>.</summary>
- /// <remarks>Return the underlying <tt>NbtAddress</tt> or <tt>InetAddress</tt>.</remarks>
- public virtual object GetAddress()
- {
- return Addr;
- }
-
- /// <summary>Return the hostname of this address such as "MYCOMPUTER".</summary>
- /// <remarks>Return the hostname of this address such as "MYCOMPUTER".</remarks>
- public virtual string GetHostName()
- {
- if (Addr is NbtAddress)
- {
- return ((NbtAddress)Addr).GetHostName();
- }
- return ((IPAddress) Addr).GetHostAddress();
- }
-
- /// <summary>Return the IP address as text such as "192.168.1.15".</summary>
- /// <remarks>Return the IP address as text such as "192.168.1.15".</remarks>
- public virtual string GetHostAddress()
- {
- if (Addr is NbtAddress)
- {
- return ((NbtAddress)Addr).GetHostAddress();
- }
- return ((IPAddress)Addr).GetHostAddress();
- }
-
- public virtual IPAddress GetHostIpAddress()
- {
- return (IPAddress) Addr;
- }
-
- /// <summary>
- /// Return the a text representation of this address such as
- /// <tt>MYCOMPUTER/192.168.1.15</tt>.
- /// </summary>
- /// <remarks>
- /// Return the a text representation of this address such as
- /// <tt>MYCOMPUTER/192.168.1.15</tt>.
- /// </remarks>
- public override string ToString()
- {
- return Addr.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs
deleted file mode 100644
index 4770f1354..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Text;
-
-namespace SharpCifs.Util
-{
- public class Base64
- {
- private static readonly string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
- /// <summary>Base-64 encodes the supplied block of data.</summary>
- /// <remarks>
- /// Base-64 encodes the supplied block of data. Line wrapping is not
- /// applied on output.
- /// </remarks>
- /// <param name="bytes">The block of data that is to be Base-64 encoded.</param>
- /// <returns>A <code>String</code> containing the encoded data.</returns>
- public static string Encode(byte[] bytes)
- {
- int length = bytes.Length;
- if (length == 0)
- {
- return string.Empty;
- }
- StringBuilder buffer = new StringBuilder((int)Math.Ceiling(length / 3d) * 4);
- int remainder = length % 3;
- length -= remainder;
- int block;
- int i = 0;
- while (i < length)
- {
- block = ((bytes[i++] & unchecked(0xff)) << 16) | ((bytes[i++] & unchecked(
- 0xff)) << 8) | (bytes[i++] & unchecked(0xff));
- buffer.Append(Alphabet[(int)(((uint)block) >> 18)]);
- buffer.Append(Alphabet[((int)(((uint)block) >> 12)) & unchecked(0x3f)]);
- buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]);
- buffer.Append(Alphabet[block & unchecked(0x3f)]);
- }
- if (remainder == 0)
- {
- return buffer.ToString();
- }
- if (remainder == 1)
- {
- block = (bytes[i] & unchecked(0xff)) << 4;
- buffer.Append(Alphabet[(int)(((uint)block) >> 6)]);
- buffer.Append(Alphabet[block & unchecked(0x3f)]);
- buffer.Append("==");
- return buffer.ToString();
- }
- block = (((bytes[i++] & unchecked(0xff)) << 8) | ((bytes[i]) & unchecked(0xff))) << 2;
- buffer.Append(Alphabet[(int)(((uint)block) >> 12)]);
- buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]);
- buffer.Append(Alphabet[block & unchecked(0x3f)]);
- buffer.Append("=");
- return buffer.ToString();
- }
-
- /// <summary>Decodes the supplied Base-64 encoded string.</summary>
- /// <remarks>Decodes the supplied Base-64 encoded string.</remarks>
- /// <param name="string">The Base-64 encoded string that is to be decoded.</param>
- /// <returns>A <code>byte[]</code> containing the decoded data block.</returns>
- public static byte[] Decode(string @string)
- {
- int length = @string.Length;
- if (length == 0)
- {
- return new byte[0];
- }
- int pad = (@string[length - 2] == '=') ? 2 : (@string[length - 1] == '=') ? 1 : 0;
- int size = length * 3 / 4 - pad;
- byte[] buffer = new byte[size];
- int block;
- int i = 0;
- int index = 0;
- while (i < length)
- {
- block = (Alphabet.IndexOf(@string[i++]) & unchecked(0xff)) << 18 | (Alphabet
- .IndexOf(@string[i++]) & unchecked(0xff)) << 12 | (Alphabet.IndexOf(@string
- [i++]) & unchecked(0xff)) << 6 | (Alphabet.IndexOf(@string[i++]) & unchecked(
- 0xff));
- buffer[index++] = unchecked((byte)((int)(((uint)block) >> 16)));
- if (index < size)
- {
- buffer[index++] = unchecked((byte)(((int)(((uint)block) >> 8)) & unchecked(0xff)));
- }
- if (index < size)
- {
- buffer[index++] = unchecked((byte)(block & unchecked(0xff)));
- }
- }
- return buffer;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs
deleted file mode 100644
index c23b14cf8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs
+++ /dev/null
@@ -1,568 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-
-namespace SharpCifs.Util
-{
- /// <summary>
- /// This code is derived from the above source
- /// JCIFS API
- /// Norbert Hranitzky
- /// <p>and modified again by Michael B.
- /// </summary>
- /// <remarks>
- /// This code is derived from the above source
- /// JCIFS API
- /// Norbert Hranitzky
- /// <p>and modified again by Michael B. Allen
- /// </remarks>
- public class DES
- {
- private int[] _encryptKeys = new int[32];
-
- private int[] _decryptKeys = new int[32];
-
- private int[] _tempInts = new int[2];
-
- public DES()
- {
- }
-
- public DES(byte[] key)
- {
- // DesCipher - the DES encryption method
- //
- // The meat of this code is by Dave Zimmerman <dzimm@widget.com>, and is:
- //
- // Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved.
- //
- // Permission to use, copy, modify, and distribute this software
- // and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
- // without fee is hereby granted, provided that this copyright notice is kept
- // intact.
- //
- // WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY
- // OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
- // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE
- // FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
- // DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
- //
- // THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
- // CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
- // PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
- // NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
- // SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
- // SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
- // PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP
- // SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
- // HIGH RISK ACTIVITIES.
- //
- //
- // The rest is:
- //
- // Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved.
- //
- // Copyright (C) 1996 by Wolfgang Platzer
- // email: wplatzer@iaik.tu-graz.ac.at
- //
- // All rights reserved.
- //
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions
- // are met:
- // 1. Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // 2. Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- //
- // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- // SUCH DAMAGE.
- //
- // Constructor, byte-array key.
- if (key.Length == 7)
- {
- byte[] key8 = new byte[8];
- MakeSmbKey(key, key8);
- SetKey(key8);
- }
- else
- {
- SetKey(key);
- }
- }
-
- public static void MakeSmbKey(byte[] key7, byte[] key8)
- {
- int i;
- key8[0] = unchecked((byte)((key7[0] >> 1) & unchecked(0xff)));
- key8[1] = unchecked((byte)((((key7[0] & unchecked(0x01)) << 6) | (((key7[1
- ] & unchecked(0xff)) >> 2) & unchecked(0xff))) & unchecked(0xff)));
- key8[2] = unchecked((byte)((((key7[1] & unchecked(0x03)) << 5) | (((key7[2
- ] & unchecked(0xff)) >> 3) & unchecked(0xff))) & unchecked(0xff)));
- key8[3] = unchecked((byte)((((key7[2] & unchecked(0x07)) << 4) | (((key7[3
- ] & unchecked(0xff)) >> 4) & unchecked(0xff))) & unchecked(0xff)));
- key8[4] = unchecked((byte)((((key7[3] & unchecked(0x0F)) << 3) | (((key7[4
- ] & unchecked(0xff)) >> 5) & unchecked(0xff))) & unchecked(0xff)));
- key8[5] = unchecked((byte)((((key7[4] & unchecked(0x1F)) << 2) | (((key7[5
- ] & unchecked(0xff)) >> 6) & unchecked(0xff))) & unchecked(0xff)));
- key8[6] = unchecked((byte)((((key7[5] & unchecked(0x3F)) << 1) | (((key7[6
- ] & unchecked(0xff)) >> 7) & unchecked(0xff))) & unchecked(0xff)));
- key8[7] = unchecked((byte)(key7[6] & unchecked(0x7F)));
- for (i = 0; i < 8; i++)
- {
- key8[i] = unchecked((byte)(key8[i] << 1));
- }
- }
-
- /// Set the key.
- public virtual void SetKey(byte[] key)
- {
- // CHECK PAROTY TBD
- Deskey(key, true, _encryptKeys);
- Deskey(key, false, _decryptKeys);
- }
-
- // Turn an 8-byte key into internal keys.
- private void Deskey(byte[] keyBlock, bool encrypting, int[] knL)
- {
- int i;
- int j;
- int l;
- int m;
- int n;
- int[] pc1M = new int[56];
- int[] pcr = new int[56];
- int[] kn = new int[32];
- for (j = 0; j < 56; ++j)
- {
- l = _pc1[j];
- m = l & 0x7;
- pc1M[j] = ((keyBlock[(int)(((uint)l) >> 3)] & _bytebit[m]) != 0) ? 1 : 0;
- }
- for (i = 0; i < 16; ++i)
- {
- if (encrypting)
- {
- m = i << 1;
- }
- else
- {
- m = (15 - i) << 1;
- }
- n = m + 1;
- kn[m] = kn[n] = 0;
- for (j = 0; j < 28; ++j)
- {
- l = j + _totrot[i];
- if (l < 28)
- {
- pcr[j] = pc1M[l];
- }
- else
- {
- pcr[j] = pc1M[l - 28];
- }
- }
- for (j = 28; j < 56; ++j)
- {
- l = j + _totrot[i];
- if (l < 56)
- {
- pcr[j] = pc1M[l];
- }
- else
- {
- pcr[j] = pc1M[l - 28];
- }
- }
- for (j = 0; j < 24; ++j)
- {
- if (pcr[_pc2[j]] != 0)
- {
- kn[m] |= _bigbyte[j];
- }
- if (pcr[_pc2[j + 24]] != 0)
- {
- kn[n] |= _bigbyte[j];
- }
- }
- }
- Cookey(kn, knL);
- }
-
- private void Cookey(int[] raw, int[] knL)
- {
- int raw0;
- int raw1;
- int rawi;
- int knLi;
- int i;
- for (i = 0, rawi = 0, knLi = 0; i < 16; ++i)
- {
- raw0 = raw[rawi++];
- raw1 = raw[rawi++];
- knL[knLi] = (raw0 & unchecked(0x00fc0000)) << 6;
- knL[knLi] |= (raw0 & unchecked(0x00000fc0)) << 10;
- knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x00fc0000))) >> 10);
- knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x00000fc0))) >> 6);
- ++knLi;
- knL[knLi] = (raw0 & unchecked(0x0003f000)) << 12;
- knL[knLi] |= (raw0 & unchecked(0x0000003f)) << 16;
- knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x0003f000))) >> 4);
- knL[knLi] |= (raw1 & unchecked(0x0000003f));
- ++knLi;
- }
- }
-
- /// Encrypt a block of eight bytes.
- private void Encrypt(byte[] clearText, int clearOff, byte[] cipherText, int cipherOff
- )
- {
- SquashBytesToInts(clearText, clearOff, _tempInts, 0, 2);
- Des(_tempInts, _tempInts, _encryptKeys);
- SpreadIntsToBytes(_tempInts, 0, cipherText, cipherOff, 2);
- }
-
- /// Decrypt a block of eight bytes.
- private void Decrypt(byte[] cipherText, int cipherOff, byte[] clearText, int clearOff
- )
- {
- SquashBytesToInts(cipherText, cipherOff, _tempInts, 0, 2);
- Des(_tempInts, _tempInts, _decryptKeys);
- SpreadIntsToBytes(_tempInts, 0, clearText, clearOff, 2);
- }
-
- // The DES function.
- private void Des(int[] inInts, int[] outInts, int[] keys)
- {
- int fval;
- int work;
- int right;
- int leftt;
- int round;
- int keysi = 0;
- leftt = inInts[0];
- right = inInts[1];
- work = (((int)(((uint)leftt) >> 4)) ^ right) & unchecked(0x0f0f0f0f);
- right ^= work;
- leftt ^= (work << 4);
- work = (((int)(((uint)leftt) >> 16)) ^ right) & unchecked(0x0000ffff);
- right ^= work;
- leftt ^= (work << 16);
- work = (((int)(((uint)right) >> 2)) ^ leftt) & unchecked(0x33333333);
- leftt ^= work;
- right ^= (work << 2);
- work = (((int)(((uint)right) >> 8)) ^ leftt) & unchecked(0x00ff00ff);
- leftt ^= work;
- right ^= (work << 8);
- right = (right << 1) | (((int)(((uint)right) >> 31)) & 1);
- work = (leftt ^ right) & unchecked((int)(0xaaaaaaaa));
- leftt ^= work;
- right ^= work;
- leftt = (leftt << 1) | (((int)(((uint)leftt) >> 31)) & 1);
- for (round = 0; round < 8; ++round)
- {
- work = (right << 28) | ((int)(((uint)right) >> 4));
- work ^= keys[keysi++];
- fval = _sp7[work & unchecked(0x0000003f)];
- fval |= _sp5[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)];
- fval |= _sp3[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)];
- fval |= _sp1[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)];
- work = right ^ keys[keysi++];
- fval |= _sp8[work & unchecked(0x0000003f)];
- fval |= _sp6[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)];
- fval |= _sp4[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)];
- fval |= _sp2[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)];
- leftt ^= fval;
- work = (leftt << 28) | ((int)(((uint)leftt) >> 4));
- work ^= keys[keysi++];
- fval = _sp7[work & unchecked(0x0000003f)];
- fval |= _sp5[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)];
- fval |= _sp3[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)];
- fval |= _sp1[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)];
- work = leftt ^ keys[keysi++];
- fval |= _sp8[work & unchecked(0x0000003f)];
- fval |= _sp6[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)];
- fval |= _sp4[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)];
- fval |= _sp2[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)];
- right ^= fval;
- }
- right = (right << 31) | ((int)(((uint)right) >> 1));
- work = (leftt ^ right) & unchecked((int)(0xaaaaaaaa));
- leftt ^= work;
- right ^= work;
- leftt = (leftt << 31) | ((int)(((uint)leftt) >> 1));
- work = (((int)(((uint)leftt) >> 8)) ^ right) & unchecked(0x00ff00ff);
- right ^= work;
- leftt ^= (work << 8);
- work = (((int)(((uint)leftt) >> 2)) ^ right) & unchecked(0x33333333);
- right ^= work;
- leftt ^= (work << 2);
- work = (((int)(((uint)right) >> 16)) ^ leftt) & unchecked(0x0000ffff);
- leftt ^= work;
- right ^= (work << 16);
- work = (((int)(((uint)right) >> 4)) ^ leftt) & unchecked(0x0f0f0f0f);
- leftt ^= work;
- right ^= (work << 4);
- outInts[0] = right;
- outInts[1] = leftt;
- }
-
- /// Encrypt a block of bytes.
- public virtual void Encrypt(byte[] clearText, byte[] cipherText)
- {
- Encrypt(clearText, 0, cipherText, 0);
- }
-
- /// Decrypt a block of bytes.
- public virtual void Decrypt(byte[] cipherText, byte[] clearText)
- {
- Decrypt(cipherText, 0, clearText, 0);
- }
-
- /// <summary>encrypts an array where the length must be a multiple of 8</summary>
- public virtual byte[] Encrypt(byte[] clearText)
- {
- int length = clearText.Length;
- if (length % 8 != 0)
- {
- Console.Out.WriteLine("Array must be a multiple of 8");
- return null;
- }
- byte[] cipherText = new byte[length];
- int count = length / 8;
- for (int i = 0; i < count; i++)
- {
- Encrypt(clearText, i * 8, cipherText, i * 8);
- }
- return cipherText;
- }
-
- /// <summary>decrypts an array where the length must be a multiple of 8</summary>
- public virtual byte[] Decrypt(byte[] cipherText)
- {
- int length = cipherText.Length;
- if (length % 8 != 0)
- {
- Console.Out.WriteLine("Array must be a multiple of 8");
- return null;
- }
- byte[] clearText = new byte[length];
- int count = length / 8;
- for (int i = 0; i < count; i++)
- {
- Encrypt(cipherText, i * 8, clearText, i * 8);
- }
- return clearText;
- }
-
- private static byte[] _bytebit = { unchecked(unchecked(0x80)), unchecked(unchecked(0x40)), unchecked(unchecked(0x20)), unchecked(unchecked(0x10)), unchecked(unchecked(0x08)), unchecked(unchecked(0x04)), unchecked(unchecked(0x02)), unchecked(unchecked(0x01)) };
-
- private static int[] _bigbyte = { unchecked(0x800000), unchecked(
- 0x400000), unchecked(0x200000), unchecked(0x100000), unchecked(
- 0x080000), unchecked(0x040000), unchecked(0x020000), unchecked(
- 0x010000), unchecked(0x008000), unchecked(0x004000), unchecked(
- 0x002000), unchecked(0x001000), unchecked(0x000800), unchecked(
- 0x000400), unchecked(0x000200), unchecked(0x000100), unchecked(
- 0x000080), unchecked(0x000040), unchecked(0x000020), unchecked(
- 0x000010), unchecked(0x000008), unchecked(0x000004), unchecked(
- 0x000002), unchecked(0x000001) };
-
- private static byte[] _pc1 = { unchecked(56), unchecked(48)
- , unchecked(40), unchecked(32), unchecked(24), unchecked(16), unchecked(8), unchecked(0), unchecked(57), unchecked(49), unchecked(41), unchecked(33), unchecked(25), unchecked(17), unchecked(9), unchecked(1), unchecked(58), unchecked(
- 50), unchecked(42), unchecked(34), unchecked(26), unchecked(
- 18), unchecked(10), unchecked(2), unchecked(59), unchecked(
- 51), unchecked(43), unchecked(35), unchecked(62), unchecked(
- 54), unchecked(46), unchecked(38), unchecked(30), unchecked(
- 22), unchecked(14), unchecked(6), unchecked(61), unchecked(
- 53), unchecked(45), unchecked(37), unchecked(29), unchecked(
- 21), unchecked(13), unchecked(5), unchecked(60), unchecked(
- 52), unchecked(44), unchecked(36), unchecked(28), unchecked(
- 20), unchecked(12), unchecked(4), unchecked(27), unchecked(
- 19), unchecked(11), unchecked(3) };
-
- private static int[] _totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19,
- 21, 23, 25, 27, 28 };
-
- private static byte[] _pc2 = { unchecked(13), unchecked(16)
- , unchecked(10), unchecked(23), unchecked(0), unchecked(4), unchecked(2), unchecked(27), unchecked(14), unchecked(5), unchecked(20), unchecked(9), unchecked(22), unchecked(18), unchecked(11), unchecked(3), unchecked(25), unchecked(7), unchecked(15), unchecked(6), unchecked(26), unchecked(19), unchecked(12), unchecked(1), unchecked(40), unchecked(51), unchecked(30), unchecked(36), unchecked(46), unchecked(54), unchecked(29), unchecked(39), unchecked(50), unchecked(
- 44), unchecked(32), unchecked(47), unchecked(43), unchecked(
- 48), unchecked(38), unchecked(55), unchecked(33), unchecked(
- 52), unchecked(45), unchecked(41), unchecked(49), unchecked(
- 35), unchecked(28), unchecked(31) };
-
- private static int[] _sp1 = { unchecked(0x01010400), unchecked(0x00000000), unchecked(0x00010000), unchecked(0x01010404), unchecked(
- 0x01010004), unchecked(0x00010404), unchecked(0x00000004),
- unchecked(0x00010000), unchecked(0x00000400), unchecked(0x01010400), unchecked(0x01010404), unchecked(0x00000400), unchecked(0x01000404), unchecked(0x01010004), unchecked(0x01000000), unchecked(
- 0x00000004), unchecked(0x00000404), unchecked(0x01000400),
- unchecked(0x01000400), unchecked(0x00010400), unchecked(0x00010400), unchecked(0x01010000), unchecked(0x01010000), unchecked(0x01000404), unchecked(0x00010004), unchecked(0x01000004), unchecked(
- 0x01000004), unchecked(0x00010004), unchecked(0x00000000),
- unchecked(0x00000404), unchecked(0x00010404), unchecked(0x01000000), unchecked(0x00010000), unchecked(0x01010404), unchecked(0x00000004), unchecked(0x01010000), unchecked(0x01010400), unchecked(
- 0x01000000), unchecked(0x01000000), unchecked(0x00000400),
- unchecked(0x01010004), unchecked(0x00010000), unchecked(0x00010400), unchecked(0x01000004), unchecked(0x00000400), unchecked(0x00000004), unchecked(0x01000404), unchecked(0x00010404), unchecked(
- 0x01010404), unchecked(0x00010004), unchecked(0x01010000),
- unchecked(0x01000404), unchecked(0x01000004), unchecked(0x00000404), unchecked(0x00010404), unchecked(0x01010400), unchecked(0x00000404), unchecked(0x01000400), unchecked(0x01000400), unchecked(
- 0x00000000), unchecked(0x00010004), unchecked(0x00010400),
- unchecked(0x00000000), unchecked(0x01010004) };
-
- private static int[] _sp2 = { unchecked((int)(0x80108020)), unchecked((int
- )(0x80008000)), unchecked(0x00008000), unchecked(0x00108020), unchecked(
- 0x00100000), unchecked(0x00000020), unchecked((int)(0x80100020)),
- unchecked((int)(0x80008020)), unchecked((int)(0x80000020)), unchecked((int)(0x80108020
- )), unchecked((int)(0x80108000)), unchecked((int)(0x80000000)), unchecked((int)(
- 0x80008000)), unchecked(0x00100000), unchecked(0x00000020), unchecked(
- (int)(0x80100020)), unchecked(0x00108000), unchecked(0x00100020),
- unchecked((int)(0x80008020)), unchecked(0x00000000), unchecked((int)(0x80000000
- )), unchecked(0x00008000), unchecked(0x00108020), unchecked((int)(
- 0x80100000)), unchecked(0x00100020), unchecked((int)(0x80000020)), unchecked(
- 0x00000000), unchecked(0x00108000), unchecked(0x00008020),
- unchecked((int)(0x80108000)), unchecked((int)(0x80100000)), unchecked(0x00008020), unchecked(0x00000000), unchecked(0x00108020), unchecked((int)(
- 0x80100020)), unchecked(0x00100000), unchecked((int)(0x80008020)), unchecked(
- (int)(0x80100000)), unchecked((int)(0x80108000)), unchecked(0x00008000),
- unchecked((int)(0x80100000)), unchecked((int)(0x80008000)), unchecked(0x00000020), unchecked((int)(0x80108020)), unchecked(0x00108020), unchecked(0x00000020), unchecked(0x00008000), unchecked((int)(0x80000000)), unchecked(
- 0x00008020), unchecked((int)(0x80108000)), unchecked(0x00100000),
- unchecked((int)(0x80000020)), unchecked(0x00100020), unchecked((int)(0x80008020
- )), unchecked((int)(0x80000020)), unchecked(0x00100020), unchecked(0x00108000), unchecked(0x00000000), unchecked((int)(0x80008000)), unchecked(
- 0x00008020), unchecked((int)(0x80000000)), unchecked((int)(0x80100020)),
- unchecked((int)(0x80108020)), unchecked(0x00108000) };
-
- private static int[] _sp3 = { unchecked(0x00000208), unchecked(0x08020200), unchecked(0x00000000), unchecked(0x08020008), unchecked(
- 0x08000200), unchecked(0x00000000), unchecked(0x00020208),
- unchecked(0x08000200), unchecked(0x00020008), unchecked(0x08000008), unchecked(0x08000008), unchecked(0x00020000), unchecked(0x08020208), unchecked(0x00020008), unchecked(0x08020000), unchecked(
- 0x00000208), unchecked(0x08000000), unchecked(0x00000008),
- unchecked(0x08020200), unchecked(0x00000200), unchecked(0x00020200), unchecked(0x08020000), unchecked(0x08020008), unchecked(0x00020208), unchecked(0x08000208), unchecked(0x00020200), unchecked(
- 0x00020000), unchecked(0x08000208), unchecked(0x00000008),
- unchecked(0x08020208), unchecked(0x00000200), unchecked(0x08000000), unchecked(0x08020200), unchecked(0x08000000), unchecked(0x00020008), unchecked(0x00000208), unchecked(0x00020000), unchecked(
- 0x08020200), unchecked(0x08000200), unchecked(0x00000000),
- unchecked(0x00000200), unchecked(0x00020008), unchecked(0x08020208), unchecked(0x08000200), unchecked(0x08000008), unchecked(0x00000200), unchecked(0x00000000), unchecked(0x08020008), unchecked(
- 0x08000208), unchecked(0x00020000), unchecked(0x08000000),
- unchecked(0x08020208), unchecked(0x00000008), unchecked(0x00020208), unchecked(0x00020200), unchecked(0x08000008), unchecked(0x08020000), unchecked(0x08000208), unchecked(0x00000208), unchecked(
- 0x08020000), unchecked(0x00020208), unchecked(0x00000008),
- unchecked(0x08020008), unchecked(0x00020200) };
-
- private static int[] _sp4 = { unchecked(0x00802001), unchecked(0x00002081), unchecked(0x00002081), unchecked(0x00000080), unchecked(
- 0x00802080), unchecked(0x00800081), unchecked(0x00800001),
- unchecked(0x00002001), unchecked(0x00000000), unchecked(0x00802000), unchecked(0x00802000), unchecked(0x00802081), unchecked(0x00000081), unchecked(0x00000000), unchecked(0x00800080), unchecked(
- 0x00800001), unchecked(0x00000001), unchecked(0x00002000),
- unchecked(0x00800000), unchecked(0x00802001), unchecked(0x00000080), unchecked(0x00800000), unchecked(0x00002001), unchecked(0x00002080), unchecked(0x00800081), unchecked(0x00000001), unchecked(
- 0x00002080), unchecked(0x00800080), unchecked(0x00002000),
- unchecked(0x00802080), unchecked(0x00802081), unchecked(0x00000081), unchecked(0x00800080), unchecked(0x00800001), unchecked(0x00802000), unchecked(0x00802081), unchecked(0x00000081), unchecked(
- 0x00000000), unchecked(0x00000000), unchecked(0x00802000),
- unchecked(0x00002080), unchecked(0x00800080), unchecked(0x00800081), unchecked(0x00000001), unchecked(0x00802001), unchecked(0x00002081), unchecked(0x00002081), unchecked(0x00000080), unchecked(
- 0x00802081), unchecked(0x00000081), unchecked(0x00000001),
- unchecked(0x00002000), unchecked(0x00800001), unchecked(0x00002001), unchecked(0x00802080), unchecked(0x00800081), unchecked(0x00002001), unchecked(0x00002080), unchecked(0x00800000), unchecked(
- 0x00802001), unchecked(0x00000080), unchecked(0x00800000),
- unchecked(0x00002000), unchecked(0x00802080) };
-
- private static int[] _sp5 = { unchecked(0x00000100), unchecked(0x02080100), unchecked(0x02080000), unchecked(0x42000100), unchecked(
- 0x00080000), unchecked(0x00000100), unchecked(0x40000000),
- unchecked(0x02080000), unchecked(0x40080100), unchecked(0x00080000), unchecked(0x02000100), unchecked(0x40080100), unchecked(0x42000100), unchecked(0x42080000), unchecked(0x00080100), unchecked(
- 0x40000000), unchecked(0x02000000), unchecked(0x40080000),
- unchecked(0x40080000), unchecked(0x00000000), unchecked(0x40000100), unchecked(0x42080100), unchecked(0x42080100), unchecked(0x02000100), unchecked(0x42080000), unchecked(0x40000100), unchecked(
- 0x00000000), unchecked(0x42000000), unchecked(0x02080100),
- unchecked(0x02000000), unchecked(0x42000000), unchecked(0x00080100), unchecked(0x00080000), unchecked(0x42000100), unchecked(0x00000100), unchecked(0x02000000), unchecked(0x40000000), unchecked(
- 0x02080000), unchecked(0x42000100), unchecked(0x40080100),
- unchecked(0x02000100), unchecked(0x40000000), unchecked(0x42080000), unchecked(0x02080100), unchecked(0x40080100), unchecked(0x00000100), unchecked(0x02000000), unchecked(0x42080000), unchecked(
- 0x42080100), unchecked(0x00080100), unchecked(0x42000000),
- unchecked(0x42080100), unchecked(0x02080000), unchecked(0x00000000), unchecked(0x40080000), unchecked(0x42000000), unchecked(0x00080100), unchecked(0x02000100), unchecked(0x40000100), unchecked(
- 0x00080000), unchecked(0x00000000), unchecked(0x40080000),
- unchecked(0x02080100), unchecked(0x40000100) };
-
- private static int[] _sp6 = { unchecked(0x20000010), unchecked(0x20400000), unchecked(0x00004000), unchecked(0x20404010), unchecked(
- 0x20400000), unchecked(0x00000010), unchecked(0x20404010),
- unchecked(0x00400000), unchecked(0x20004000), unchecked(0x00404010), unchecked(0x00400000), unchecked(0x20000010), unchecked(0x00400010), unchecked(0x20004000), unchecked(0x20000000), unchecked(
- 0x00004010), unchecked(0x00000000), unchecked(0x00400010),
- unchecked(0x20004010), unchecked(0x00004000), unchecked(0x00404000), unchecked(0x20004010), unchecked(0x00000010), unchecked(0x20400010), unchecked(0x20400010), unchecked(0x00000000), unchecked(
- 0x00404010), unchecked(0x20404000), unchecked(0x00004010),
- unchecked(0x00404000), unchecked(0x20404000), unchecked(0x20000000), unchecked(0x20004000), unchecked(0x00000010), unchecked(0x20400010), unchecked(0x00404000), unchecked(0x20404010), unchecked(
- 0x00400000), unchecked(0x00004010), unchecked(0x20000010),
- unchecked(0x00400000), unchecked(0x20004000), unchecked(0x20000000), unchecked(0x00004010), unchecked(0x20000010), unchecked(0x20404010), unchecked(0x00404000), unchecked(0x20400000), unchecked(
- 0x00404010), unchecked(0x20404000), unchecked(0x00000000),
- unchecked(0x20400010), unchecked(0x00000010), unchecked(0x00004000), unchecked(0x20400000), unchecked(0x00404010), unchecked(0x00004000), unchecked(0x00400010), unchecked(0x20004010), unchecked(
- 0x00000000), unchecked(0x20404000), unchecked(0x20000000),
- unchecked(0x00400010), unchecked(0x20004010) };
-
- private static int[] _sp7 = { unchecked(0x00200000), unchecked(0x04200002), unchecked(0x04000802), unchecked(0x00000000), unchecked(
- 0x00000800), unchecked(0x04000802), unchecked(0x00200802),
- unchecked(0x04200800), unchecked(0x04200802), unchecked(0x00200000), unchecked(0x00000000), unchecked(0x04000002), unchecked(0x00000002), unchecked(0x04000000), unchecked(0x04200002), unchecked(
- 0x00000802), unchecked(0x04000800), unchecked(0x00200802),
- unchecked(0x00200002), unchecked(0x04000800), unchecked(0x04000002), unchecked(0x04200000), unchecked(0x04200800), unchecked(0x00200002), unchecked(0x04200000), unchecked(0x00000800), unchecked(
- 0x00000802), unchecked(0x04200802), unchecked(0x00200800),
- unchecked(0x00000002), unchecked(0x04000000), unchecked(0x00200800), unchecked(0x04000000), unchecked(0x00200800), unchecked(0x00200000), unchecked(0x04000802), unchecked(0x04000802), unchecked(
- 0x04200002), unchecked(0x04200002), unchecked(0x00000002),
- unchecked(0x00200002), unchecked(0x04000000), unchecked(0x04000800), unchecked(0x00200000), unchecked(0x04200800), unchecked(0x00000802), unchecked(0x00200802), unchecked(0x04200800), unchecked(
- 0x00000802), unchecked(0x04000002), unchecked(0x04200802),
- unchecked(0x04200000), unchecked(0x00200800), unchecked(0x00000000), unchecked(0x00000002), unchecked(0x04200802), unchecked(0x00000000), unchecked(0x00200802), unchecked(0x04200000), unchecked(
- 0x00000800), unchecked(0x04000002), unchecked(0x04000800),
- unchecked(0x00000800), unchecked(0x00200002) };
-
- private static int[] _sp8 = { unchecked(0x10001040), unchecked(0x00001000), unchecked(0x00040000), unchecked(0x10041040), unchecked(
- 0x10000000), unchecked(0x10001040), unchecked(0x00000040),
- unchecked(0x10000000), unchecked(0x00040040), unchecked(0x10040000), unchecked(0x10041040), unchecked(0x00041000), unchecked(0x10041000), unchecked(0x00041040), unchecked(0x00001000), unchecked(
- 0x00000040), unchecked(0x10040000), unchecked(0x10000040),
- unchecked(0x10001000), unchecked(0x00001040), unchecked(0x00041000), unchecked(0x00040040), unchecked(0x10040040), unchecked(0x10041000), unchecked(0x00001040), unchecked(0x00000000), unchecked(
- 0x00000000), unchecked(0x10040040), unchecked(0x10000040),
- unchecked(0x10001000), unchecked(0x00041040), unchecked(0x00040000), unchecked(0x00041040), unchecked(0x00040000), unchecked(0x10041000), unchecked(0x00001000), unchecked(0x00000040), unchecked(
- 0x10040040), unchecked(0x00001000), unchecked(0x00041040),
- unchecked(0x10001000), unchecked(0x00000040), unchecked(0x10000040), unchecked(0x10040000), unchecked(0x10040040), unchecked(0x10000000), unchecked(0x00040000), unchecked(0x10001040), unchecked(
- 0x00000000), unchecked(0x10041040), unchecked(0x00040040),
- unchecked(0x10000040), unchecked(0x10040000), unchecked(0x10001000), unchecked(0x10001040), unchecked(0x00000000), unchecked(0x10041040), unchecked(0x00041000), unchecked(0x00041000), unchecked(
- 0x00001040), unchecked(0x00001040), unchecked(0x00040040),
- unchecked(0x10000000), unchecked(0x10041000) };
-
- // Tables, permutations, S-boxes, etc.
- /// Squash bytes down to ints.
- public static void SquashBytesToInts(byte[] inBytes, int inOff, int[] outInts, int
- outOff, int intLen)
- {
- for (int i = 0; i < intLen; ++i)
- {
- outInts[outOff + i] = ((inBytes[inOff + i * 4] & unchecked(0xff)) << 24) |
- ((inBytes[inOff + i * 4 + 1] & unchecked(0xff)) << 16) | ((inBytes[inOff
- + i * 4 + 2] & unchecked(0xff)) << 8) | (inBytes[inOff + i * 4 + 3] & unchecked(
- 0xff));
- }
- }
-
- /// Spread ints into bytes.
- public static void SpreadIntsToBytes(int[] inInts, int inOff, byte[] outBytes, int
- outOff, int intLen)
- {
- for (int i = 0; i < intLen; ++i)
- {
- outBytes[outOff + i * 4] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >> 24
- )));
- outBytes[outOff + i * 4 + 1] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >>
- 16)));
- outBytes[outOff + i * 4 + 2] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >>
- 8)));
- outBytes[outOff + i * 4 + 3] = unchecked((byte)inInts[inOff + i]);
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs
deleted file mode 100644
index 7e4d57705..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs
+++ /dev/null
@@ -1,401 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util
-{
- public class Encdec
- {
- public const long MillisecondsBetween1970And1601 = 11644473600000L;
-
- public const long SecBetweeen1904And1970 = 2082844800L;
-
- public const int Time1970Sec32Be = 1;
-
- public const int Time1970Sec32Le = 2;
-
- public const int Time1904Sec32Be = 3;
-
- public const int Time1904Sec32Le = 4;
-
- public const int Time1601Nanos64Le = 5;
-
- public const int Time1601Nanos64Be = 6;
-
- public const int Time1970Millis64Be = 7;
-
- public const int Time1970Millis64Le = 8;
-
- public static int Enc_uint16be(short s, byte[] dst, int di)
- {
- dst[di++] = unchecked((byte)((s >> 8) & unchecked(0xFF)));
- dst[di] = unchecked((byte)(s & unchecked(0xFF)));
- return 2;
- }
-
- public static int Enc_uint32be(int i, byte[] dst, int di)
- {
- dst[di++] = unchecked((byte)((i >> 24) & unchecked(0xFF)));
- dst[di++] = unchecked((byte)((i >> 16) & unchecked(0xFF)));
- dst[di++] = unchecked((byte)((i >> 8) & unchecked(0xFF)));
- dst[di] = unchecked((byte)(i & unchecked(0xFF)));
- return 4;
- }
-
- public static int Enc_uint16le(short s, byte[] dst, int di)
- {
- dst[di++] = unchecked((byte)(s & unchecked(0xFF)));
- dst[di] = unchecked((byte)((s >> 8) & unchecked(0xFF)));
- return 2;
- }
-
- public static int Enc_uint32le(int i, byte[] dst, int di)
- {
- dst[di++] = unchecked((byte)(i & unchecked(0xFF)));
- dst[di++] = unchecked((byte)((i >> 8) & unchecked(0xFF)));
- dst[di++] = unchecked((byte)((i >> 16) & unchecked(0xFF)));
- dst[di] = unchecked((byte)((i >> 24) & unchecked(0xFF)));
- return 4;
- }
-
- public static short Dec_uint16be(byte[] src, int si)
- {
- return (short)(((src[si] & unchecked(0xFF)) << 8) | (src[si + 1] & unchecked(
- 0xFF)));
- }
-
- public static int Dec_uint32be(byte[] src, int si)
- {
- return ((src[si] & unchecked(0xFF)) << 24) | ((src[si + 1] & unchecked(0xFF)) << 16) | ((src[si + 2] & unchecked(0xFF)) << 8) | (src[si + 3]
- & unchecked(0xFF));
- }
-
- public static short Dec_uint16le(byte[] src, int si)
- {
- return (short)((src[si] & unchecked(0xFF)) | ((src[si + 1] & unchecked(0xFF)) << 8));
- }
-
- public static int Dec_uint32le(byte[] src, int si)
- {
- return (src[si] & unchecked(0xFF)) | ((src[si + 1] & unchecked(0xFF
- )) << 8) | ((src[si + 2] & unchecked(0xFF)) << 16) | ((src[si + 3] & unchecked(
- 0xFF)) << 24);
- }
-
- public static int Enc_uint64be(long l, byte[] dst, int di)
- {
- Enc_uint32be((int)(l & unchecked(0xFFFFFFFFL)), dst, di + 4);
- Enc_uint32be((int)((l >> 32) & unchecked(0xFFFFFFFFL)), dst, di);
- return 8;
- }
-
- public static int Enc_uint64le(long l, byte[] dst, int di)
- {
- Enc_uint32le((int)(l & unchecked(0xFFFFFFFFL)), dst, di);
- Enc_uint32le((int)((l >> 32) & unchecked(0xFFFFFFFFL)), dst, di + 4);
- return 8;
- }
-
- public static long Dec_uint64be(byte[] src, int si)
- {
- long l;
- l = Dec_uint32be(src, si) & unchecked(0xFFFFFFFFL);
- l <<= 32;
- l |= Dec_uint32be(src, si + 4) & unchecked(0xFFFFFFFFL);
- return l;
- }
-
- public static long Dec_uint64le(byte[] src, int si)
- {
- long l;
- l = Dec_uint32le(src, si + 4) & unchecked(0xFFFFFFFFL);
- l <<= 32;
- l |= Dec_uint32le(src, si) & unchecked(0xFFFFFFFFL);
- return l;
- }
-
- public static int Enc_floatle(float f, byte[] dst, int di)
- {
- return Enc_uint32le((int)BitConverter.DoubleToInt64Bits(f), dst, di);
- }
-
- public static int Enc_floatbe(float f, byte[] dst, int di)
- {
- return Enc_uint32be((int)BitConverter.DoubleToInt64Bits(f), dst, di);
- }
-
- public static float Dec_floatle(byte[] src, int si)
- {
- return (float)BitConverter.Int64BitsToDouble(Dec_uint32le(src, si));
- }
-
- public static float Dec_floatbe(byte[] src, int si)
- {
- return (float)BitConverter.Int64BitsToDouble(Dec_uint32be(src, si));
- }
-
- public static int Enc_doublele(double d, byte[] dst, int di)
- {
- return Enc_uint64le(BitConverter.DoubleToInt64Bits(d), dst, di);
- }
-
- public static int Enc_doublebe(double d, byte[] dst, int di)
- {
- return Enc_uint64be(BitConverter.DoubleToInt64Bits(d), dst, di);
- }
-
- public static double Dec_doublele(byte[] src, int si)
- {
- return BitConverter.Int64BitsToDouble(Dec_uint64le(src, si));
- }
-
- public static double Dec_doublebe(byte[] src, int si)
- {
- return BitConverter.Int64BitsToDouble(Dec_uint64be(src, si));
- }
-
- public static int Enc_time(DateTime date, byte[] dst, int di, int enc)
- {
- long t;
- switch (enc)
- {
- case Time1970Sec32Be:
- {
- return Enc_uint32be((int)(date.GetTime() / 1000L), dst, di);
- }
-
- case Time1970Sec32Le:
- {
- return Enc_uint32le((int)(date.GetTime() / 1000L), dst, di);
- }
-
- case Time1904Sec32Be:
- {
- return Enc_uint32be((int)((date.GetTime() / 1000L + SecBetweeen1904And1970) &
- unchecked((int)(0xFFFFFFFF))), dst, di);
- }
-
- case Time1904Sec32Le:
- {
- return Enc_uint32le((int)((date.GetTime() / 1000L + SecBetweeen1904And1970) &
- unchecked((int)(0xFFFFFFFF))), dst, di);
- }
-
- case Time1601Nanos64Be:
- {
- t = (date.GetTime() + MillisecondsBetween1970And1601) * 10000L;
- return Enc_uint64be(t, dst, di);
- }
-
- case Time1601Nanos64Le:
- {
- t = (date.GetTime() + MillisecondsBetween1970And1601) * 10000L;
- return Enc_uint64le(t, dst, di);
- }
-
- case Time1970Millis64Be:
- {
- return Enc_uint64be(date.GetTime(), dst, di);
- }
-
- case Time1970Millis64Le:
- {
- return Enc_uint64le(date.GetTime(), dst, di);
- }
-
- default:
- {
- throw new ArgumentException("Unsupported time encoding");
- }
- }
- }
-
- public static DateTime Dec_time(byte[] src, int si, int enc)
- {
- long t;
- switch (enc)
- {
- case Time1970Sec32Be:
- {
- return Sharpen.Extensions.CreateDate(Dec_uint32be(src, si) * 1000L);
- }
-
- case Time1970Sec32Le:
- {
- return Sharpen.Extensions.CreateDate(Dec_uint32le(src, si) * 1000L);
- }
-
- case Time1904Sec32Be:
- {
- return Sharpen.Extensions.CreateDate(((Dec_uint32be(src, si) & unchecked(0xFFFFFFFFL)) - SecBetweeen1904And1970) * 1000L);
- }
-
- case Time1904Sec32Le:
- {
- return Sharpen.Extensions.CreateDate(((Dec_uint32le(src, si) & unchecked(0xFFFFFFFFL)) - SecBetweeen1904And1970) * 1000L);
- }
-
- case Time1601Nanos64Be:
- {
- t = Dec_uint64be(src, si);
- return Sharpen.Extensions.CreateDate(t / 10000L - MillisecondsBetween1970And1601
- );
- }
-
- case Time1601Nanos64Le:
- {
- t = Dec_uint64le(src, si);
- return Sharpen.Extensions.CreateDate(t / 10000L - MillisecondsBetween1970And1601
- );
- }
-
- case Time1970Millis64Be:
- {
- return Sharpen.Extensions.CreateDate(Dec_uint64be(src, si));
- }
-
- case Time1970Millis64Le:
- {
- return Sharpen.Extensions.CreateDate(Dec_uint64le(src, si));
- }
-
- default:
- {
- throw new ArgumentException("Unsupported time encoding");
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static int Enc_utf8(string str, byte[] dst, int di, int dlim)
- {
- int start = di;
- int ch;
- int strlen = str.Length;
- for (int i = 0; di < dlim && i < strlen; i++)
- {
- ch = str[i];
- if ((ch >= unchecked(0x0001)) && (ch <= unchecked(0x007F)))
- {
- dst[di++] = unchecked((byte)ch);
- }
- else
- {
- if (ch > unchecked(0x07FF))
- {
- if ((dlim - di) < 3)
- {
- break;
- }
- dst[di++] = unchecked((byte)(unchecked(0xE0) | ((ch >> 12) & unchecked(0x0F))));
- dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 6) & unchecked(0x3F))));
- dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 0) & unchecked(0x3F))));
- }
- else
- {
- if ((dlim - di) < 2)
- {
- break;
- }
- dst[di++] = unchecked((byte)(unchecked(0xC0) | ((ch >> 6) & unchecked(0x1F))));
- dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 0) & unchecked(0x3F))));
- }
- }
- }
- return di - start;
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static string Dec_utf8(byte[] src, int si, int slim)
- {
- char[] uni = new char[slim - si];
- int ui;
- int ch;
- for (ui = 0; si < slim && (ch = src[si++] & unchecked(0xFF)) != 0; ui++)
- {
- if (ch < unchecked(0x80))
- {
- uni[ui] = (char)ch;
- }
- else
- {
- if ((ch & unchecked(0xE0)) == unchecked(0xC0))
- {
- if ((slim - si) < 2)
- {
- break;
- }
- uni[ui] = (char)((ch & unchecked(0x1F)) << 6);
- ch = src[si++] & unchecked(0xFF);
- uni[ui] |= (char)((char)ch & unchecked(0x3F));
- if ((ch & unchecked(0xC0)) != unchecked(0x80) || uni[ui] < unchecked(
- 0x80))
- {
- throw new IOException("Invalid UTF-8 sequence");
- }
- }
- else
- {
- if ((ch & unchecked(0xF0)) == unchecked(0xE0))
- {
- if ((slim - si) < 3)
- {
- break;
- }
- uni[ui] = (char)((ch & unchecked(0x0F)) << 12);
- ch = src[si++] & unchecked(0xFF);
- if ((ch & unchecked(0xC0)) != unchecked(0x80))
- {
- throw new IOException("Invalid UTF-8 sequence");
- }
- uni[ui] |= (char)((char)(ch & unchecked(0x3F)) << 6);
- ch = src[si++] & unchecked(0xFF);
- uni[ui] |= (char)((char)ch & unchecked(0x3F));
- if ((ch & unchecked(0xC0)) != unchecked(0x80) || uni[ui] < unchecked(
- 0x800))
- {
- throw new IOException("Invalid UTF-8 sequence");
- }
- }
- else
- {
- throw new IOException("Unsupported UTF-8 sequence");
- }
- }
- }
- }
- return new string(uni, 0, ui);
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static string Dec_ucs2le(byte[] src, int si, int slim, char[] buf)
- {
- int bi;
- for (bi = 0; (si + 1) < slim; bi++, si += 2)
- {
- buf[bi] = (char)Dec_uint16le(src, si);
- if (buf[bi] == '\0')
- {
- break;
- }
- }
- return new string(buf, 0, bi);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs
deleted file mode 100644
index 9ab31d61b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util
-{
- /// <summary>This is an implementation of the HMACT64 keyed hashing algorithm.</summary>
- /// <remarks>
- /// This is an implementation of the HMACT64 keyed hashing algorithm.
- /// HMACT64 is defined by Luke Leighton as a modified HMAC-MD5 (RFC 2104)
- /// in which the key is truncated at 64 bytes (rather than being hashed
- /// via MD5).
- /// </remarks>
- public class Hmact64 : MessageDigest
- {
- private const int BlockLength = 64;
-
- private const byte Ipad = unchecked(unchecked(0x36));
-
- private const byte Opad = unchecked(unchecked(0x5c));
-
- private MessageDigest _md5;
-
- private byte[] _ipad = new byte[BlockLength];
-
- private byte[] _opad = new byte[BlockLength];
-
- /// <summary>Creates an HMACT64 instance which uses the given secret key material.</summary>
- /// <remarks>Creates an HMACT64 instance which uses the given secret key material.</remarks>
- /// <param name="key">The key material to use in hashing.</param>
- public Hmact64(byte[] key)
- {
- int length = Math.Min(key.Length, BlockLength);
- for (int i = 0; i < length; i++)
- {
- _ipad[i] = unchecked((byte)(key[i] ^ Ipad));
- _opad[i] = unchecked((byte)(key[i] ^ Opad));
- }
- for (int i1 = length; i1 < BlockLength; i1++)
- {
- _ipad[i1] = Ipad;
- _opad[i1] = Opad;
- }
- try
- {
- _md5 = GetInstance("MD5");
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException(ex.Message);
- }
- EngineReset();
- }
-
-
- protected byte[] EngineDigest()
- {
- byte[] digest = _md5.Digest();
- _md5.Update(_opad);
- return _md5.Digest(digest);
- }
-
- protected int EngineDigest(byte[] buf, int offset, int len)
- {
- byte[] digest = _md5.Digest();
- _md5.Update(_opad);
- _md5.Update(digest);
- try
- {
- _md5.Digest(buf, offset, len);
-
- return len;
- }
- catch (Exception)
- {
- throw new InvalidOperationException();
- }
- }
-
- protected int EngineGetDigestLength()
- {
- return _md5.GetDigestLength();
- }
-
- protected void EngineReset()
- {
- _md5.Reset();
- _md5.Update(_ipad);
- }
-
- protected void EngineUpdate(byte b)
- {
- _md5.Update(b);
- }
-
- protected void EngineUpdate(byte[] input, int offset, int len)
- {
- _md5.Update(input, offset, len);
- }
-
- public override byte[] Digest()
- {
- return EngineDigest();
- }
-
- public override int GetDigestLength()
- {
- return EngineGetDigestLength();
- }
-
- public override void Reset()
- {
- EngineReset();
- }
-
- public override void Update(byte[] b)
- {
- EngineUpdate(b, 0, b.Length);
- }
-
- public override void Update(byte b)
- {
- EngineUpdate(b);
- }
-
- public override void Update(byte[] b, int offset, int len)
- {
- EngineUpdate(b, offset, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs
deleted file mode 100644
index 7e53f76e3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-
-namespace SharpCifs.Util
-{
- public class Hexdump
- {
- private static readonly string Nl = @"\r\n"; //Runtime.GetProperty("line.separator");
-
- private static readonly int NlLength = Nl.Length;
-
- private static readonly char[] SpaceChars = { ' ', ' ', ' ', ' ', ' '
- , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
- , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
- , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
-
- public static readonly char[] HexDigits = { '0', '1', '2', '3', '4',
- '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
-
-
- private static bool IsIsoControl(char c)
- {
- return (c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F');
- }
-
- /// <summary>
- /// Generate "hexdump" output of the buffer at src like the following:
- /// <p><blockquote><pre>
- /// 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46 |..).........
- /// </summary>
- /// <remarks>
- /// Generate "hexdump" output of the buffer at src like the following:
- /// <p><blockquote><pre>
- /// 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46 |..)......... EGF|
- /// 00010: 43 45 46 45 45 43 41 43 41 43 41 43 41 43 41 43 |CEFEECACACACACAC|
- /// 00020: 41 43 41 43 41 43 41 43 41 43 41 41 44 00 00 20 |ACACACACACAAD.. |
- /// 00030: 00 01 c0 0c 00 20 00 01 00 00 00 00 00 06 20 00 |..... ........ .|
- /// 00040: ac 22 22 e1 |."". |
- /// </blockquote></pre>
- /// </remarks>
- public static void ToHexdump(TextWriter ps, byte[] src, int srcIndex, int length)
- {
- if (length == 0)
- {
- return;
- }
- int s = length % 16;
- int r = (s == 0) ? length / 16 : length / 16 + 1;
- char[] c = new char[r * (74 + NlLength)];
- char[] d = new char[16];
- int i;
- int si = 0;
- int ci = 0;
- do
- {
- ToHexChars(si, c, ci, 5);
- ci += 5;
- c[ci++] = ':';
- do
- {
- if (si == length)
- {
- int n = 16 - s;
- Array.Copy(SpaceChars, 0, c, ci, n * 3);
- ci += n * 3;
- Array.Copy(SpaceChars, 0, d, s, n);
- break;
- }
- c[ci++] = ' ';
- i = src[srcIndex + si] & 0xFF;
- ToHexChars(i, c, ci, 2);
- ci += 2;
- if (i < 0 || IsIsoControl((char)i))
- {
- d[si % 16] = '.';
- }
- else
- {
- d[si % 16] = (char)i;
- }
- }
- while ((++si % 16) != 0);
- c[ci++] = ' ';
- c[ci++] = ' ';
- c[ci++] = '|';
- Array.Copy(d, 0, c, ci, 16);
- ci += 16;
- c[ci++] = '|';
- //Sharpen.Runtime.GetCharsForString(NL, 0, NL_LENGTH, c, ci);
- c = Nl.ToCharArray(0, NlLength);
- ci += NlLength;
- }
- while (si < length);
- ps.WriteLine(c);
- }
-
- /// <summary>
- /// This is an alternative to the <code>java.lang.Integer.toHexString</cod>
- /// method.
- /// </summary>
- /// <remarks>
- /// This is an alternative to the <code>java.lang.Integer.toHexString</cod>
- /// method. It is an efficient relative that also will pad the left side so
- /// that the result is <code>size</code> digits.
- /// </remarks>
- public static string ToHexString(int val, int size)
- {
- char[] c = new char[size];
- ToHexChars(val, c, 0, size);
- return new string(c);
- }
-
- public static string ToHexString(long val, int size)
- {
- char[] c = new char[size];
- ToHexChars(val, c, 0, size);
- return new string(c);
- }
-
- public static string ToHexString(byte[] src, int srcIndex, int size)
- {
- char[] c = new char[size];
- size = (size % 2 == 0) ? size / 2 : size / 2 + 1;
- for (int i = 0, j = 0; i < size; i++)
- {
- c[j++] = HexDigits[(src[i] >> 4) & 0x0F];
- if (j == c.Length)
- {
- break;
- }
- c[j++] = HexDigits[src[i] & 0x0F];
- }
- return new string(c);
- }
-
- /// <summary>
- /// This is the same as
- /// <see cref="ToHexString(int, int)">ToHexString(int, int)</see>
- /// but provides a more practical form when trying to avoid
- /// <see cref="string">string</see>
- /// concatenation and
- /// <see cref="System.Text.StringBuilder">System.Text.StringBuilder</see>
- /// .
- /// </summary>
- public static void ToHexChars(int val, char[] dst, int dstIndex, int size)
- {
- while (size > 0)
- {
- int i = dstIndex + size - 1;
- if (i < dst.Length)
- {
- dst[i] = HexDigits[val & 0x000F];
- }
- if (val != 0)
- {
- val = (int)(((uint)val) >> 4);
- }
- size--;
- }
- }
-
- public static void ToHexChars(long val, char[] dst, int dstIndex, int size)
- {
- while (size > 0)
- {
- dst[dstIndex + size - 1] = HexDigits[(int)(val & 0x000FL)];
- if (val != 0)
- {
- val = (long)(((ulong)val) >> 4);
- }
- size--;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs
deleted file mode 100644
index 9dd130b50..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Text;
-//using Windows.Storage;
-//using Windows.UI.Notifications;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util
-{
- /// <summary>
- /// 0 - nothing
- /// 1 - critical [default]
- /// 2 - basic info can be logged under load
- /// 3 - almost everything
- /// N - debugging
- /// </summary>
- public class LogStream: PrintWriter
-{
- private static LogStream _inst = null;
-
- public int Level = 1;
-
- public void SetLevel(int level)
- {
- this.Level = level;
- }
-
- public LogStream(TextWriter other) : base(other)
- {
-
- }
-
- /// <summary>
- /// This must be called before <tt>getInstance</tt> is called or
- /// it will have no effect.
- /// </summary>
- /// <remarks>
- /// This must be called before <tt>getInstance</tt> is called or
- /// it will have no effect.
- /// </remarks>
- public static void SetInstance(TextWriter other)
- {
- //inst = new Jcifs.Util.LogStream();
- _inst = new LogStream(other);
- }
-
- public static LogStream GetInstance()
- {
- if (_inst == null)
- {
- SetInstance(Console.Error);
- }
- return _inst;
- }
-
- public override Encoding Encoding
- {
- get { throw new NotImplementedException(); }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs
deleted file mode 100644
index 99eb6ade6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs
+++ /dev/null
@@ -1,347 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util
-{
- /// <summary>Implements the MD4 message digest algorithm in Java.</summary>
- /// <remarks>
- /// Implements the MD4 message digest algorithm in Java.
- /// <p>
- /// <b>References:</b>
- /// <ol>
- /// <li> Ronald L. Rivest,
- /// "<a href="http://www.roxen.com/rfc/rfc1320.html">
- /// The MD4 Message-Digest Algorithm</a>",
- /// IETF RFC-1320 (informational).
- /// </ol>
- /// <p><b>$Revision: 1.2 $</b>
- /// </remarks>
- /// <author>Raif S. Naffah</author>
- public class Md4 : MessageDigest
- {
- /// <summary>The size in bytes of the input block to the tranformation algorithm.</summary>
- /// <remarks>The size in bytes of the input block to the tranformation algorithm.</remarks>
- private const int BlockLength = 64;
-
- /// <summary>4 32-bit words (interim result)</summary>
- private int[] _context = new int[4];
-
- /// <summary>Number of bytes processed so far mod.</summary>
- /// <remarks>Number of bytes processed so far mod. 2 power of 64.</remarks>
- private long _count;
-
- /// <summary>512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.</summary>
- /// <remarks>512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.</remarks>
- private byte[] _buffer = new byte[BlockLength];
-
- /// <summary>512 bits work buffer = 16 x 32-bit words</summary>
- private int[] _x = new int[16];
-
- public Md4()
- {
- // This file is currently unlocked (change this line if you lock the file)
- //
- // $Log: MD4.java,v $
- // Revision 1.2 1998/01/05 03:41:19 iang
- // Added references only.
- //
- // Revision 1.1.1.1 1997/11/03 22:36:56 hopwood
- // + Imported to CVS (tagged as 'start').
- //
- // Revision 0.1.0.0 1997/07/14 R. Naffah
- // + original version
- //
- // $Endlog$
- // MD4 specific object variables
- //...........................................................................
- // = 512 / 8;
- // Constructors
- //...........................................................................
- EngineReset();
- }
-
- /// <summary>This constructor is here to implement cloneability of this class.</summary>
- /// <remarks>This constructor is here to implement cloneability of this class.</remarks>
- private Md4(Md4 md) : this()
- {
- _context = (int[])md._context.Clone();
- _buffer = (byte[])md._buffer.Clone();
- _count = md._count;
- }
-
- // Cloneable method implementation
- //...........................................................................
- /// <summary>Returns a copy of this MD object.</summary>
- /// <remarks>Returns a copy of this MD object.</remarks>
- public object Clone()
- {
- return new Md4(this);
- }
-
- // JCE methods
- //...........................................................................
- /// <summary>
- /// Resets this object disregarding any temporary data present at the
- /// time of the invocation of this call.
- /// </summary>
- /// <remarks>
- /// Resets this object disregarding any temporary data present at the
- /// time of the invocation of this call.
- /// </remarks>
- protected void EngineReset()
- {
- // initial values of MD4 i.e. A, B, C, D
- // as per rfc-1320; they are low-order byte first
- _context[0] = unchecked(0x67452301);
- _context[1] = unchecked((int)(0xEFCDAB89));
- _context[2] = unchecked((int)(0x98BADCFE));
- _context[3] = unchecked(0x10325476);
- _count = 0L;
- for (int i = 0; i < BlockLength; i++)
- {
- _buffer[i] = 0;
- }
- }
-
- /// <summary>Continues an MD4 message digest using the input byte.</summary>
- /// <remarks>Continues an MD4 message digest using the input byte.</remarks>
- protected void EngineUpdate(byte b)
- {
- // compute number of bytes still unhashed; ie. present in buffer
- int i = (int)(_count % BlockLength);
- _count++;
- // update number of bytes
- _buffer[i] = b;
- if (i == BlockLength - 1)
- {
- Transform(_buffer, 0);
- }
- }
-
- /// <summary>MD4 block update operation.</summary>
- /// <remarks>
- /// MD4 block update operation.
- /// <p>
- /// Continues an MD4 message digest operation, by filling the buffer,
- /// transform(ing) data in 512-bit message block(s), updating the variables
- /// context and count, and leaving (buffering) the remaining bytes in buffer
- /// for the next update or finish.
- /// </remarks>
- /// <param name="input">input block</param>
- /// <param name="offset">start of meaningful bytes in input</param>
- /// <param name="len">count of bytes in input block to consider</param>
- protected void EngineUpdate(byte[] input, int offset, int len)
- {
- // make sure we don't exceed input's allocated size/length
- if (offset < 0 || len < 0 || (long)offset + len > input.Length)
- {
- throw new IndexOutOfRangeException();
- }
- // compute number of bytes still unhashed; ie. present in buffer
- int bufferNdx = (int)(_count % BlockLength);
- _count += len;
- // update number of bytes
- int partLen = BlockLength - bufferNdx;
- int i = 0;
- if (len >= partLen)
- {
- Array.Copy(input, offset, _buffer, bufferNdx, partLen);
- Transform(_buffer, 0);
- for (i = partLen; i + BlockLength - 1 < len; i += BlockLength)
- {
- Transform(input, offset + i);
- }
- bufferNdx = 0;
- }
- // buffer remaining input
- if (i < len)
- {
- Array.Copy(input, offset + i, _buffer, bufferNdx, len - i);
- }
- }
-
- /// <summary>
- /// Completes the hash computation by performing final operations such
- /// as padding.
- /// </summary>
- /// <remarks>
- /// Completes the hash computation by performing final operations such
- /// as padding. At the return of this engineDigest, the MD engine is
- /// reset.
- /// </remarks>
- /// <returns>the array of bytes for the resulting hash value.</returns>
- protected byte[] EngineDigest()
- {
- // pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
- int bufferNdx = (int)(_count % BlockLength);
- int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx);
- // padding is alwas binary 1 followed by binary 0s
- byte[] tail = new byte[padLen + 8];
- tail[0] = unchecked(unchecked(0x80));
- // append length before final transform:
- // save number of bits, casting the long to an array of 8 bytes
- // save low-order byte first.
- for (int i = 0; i < 8; i++)
- {
- tail[padLen + i] = unchecked((byte)((long)(((ulong)(_count * 8)) >> (8 * i))));
- }
- EngineUpdate(tail, 0, tail.Length);
- byte[] result = new byte[16];
- // cast this MD4's context (array of 4 ints) into an array of 16 bytes.
- for (int i1 = 0; i1 < 4; i1++)
- {
- for (int j = 0; j < 4; j++)
- {
- result[i1 * 4 + j] = unchecked((byte)((int)(((uint)_context[i1]) >> (8 * j))));
- }
- }
- // reset the engine
- EngineReset();
- return result;
- }
-
- // own methods
- //...........................................................................
- /// <summary>MD4 basic transformation.</summary>
- /// <remarks>
- /// MD4 basic transformation.
- /// <p>
- /// Transforms context based on 512 bits from input block starting
- /// from the offset'th byte.
- /// </remarks>
- /// <param name="block">input sub-array.</param>
- /// <param name="offset">starting position of sub-array.</param>
- private void Transform(byte[] block, int offset)
- {
- // encodes 64 bytes from input block into an array of 16 32-bit
- // entities. Use A as a temp var.
- for (int i = 0; i < 16; i++)
- {
- _x[i] = (block[offset++] & unchecked(0xFF)) | (block[offset++] & unchecked(
- 0xFF)) << 8 | (block[offset++] & unchecked(0xFF)) << 16 | (block[offset
- ++] & unchecked(0xFF)) << 24;
- }
- int a = _context[0];
- int b = _context[1];
- int c = _context[2];
- int d = _context[3];
- a = Ff(a, b, c, d, _x[0], 3);
- d = Ff(d, a, b, c, _x[1], 7);
- c = Ff(c, d, a, b, _x[2], 11);
- b = Ff(b, c, d, a, _x[3], 19);
- a = Ff(a, b, c, d, _x[4], 3);
- d = Ff(d, a, b, c, _x[5], 7);
- c = Ff(c, d, a, b, _x[6], 11);
- b = Ff(b, c, d, a, _x[7], 19);
- a = Ff(a, b, c, d, _x[8], 3);
- d = Ff(d, a, b, c, _x[9], 7);
- c = Ff(c, d, a, b, _x[10], 11);
- b = Ff(b, c, d, a, _x[11], 19);
- a = Ff(a, b, c, d, _x[12], 3);
- d = Ff(d, a, b, c, _x[13], 7);
- c = Ff(c, d, a, b, _x[14], 11);
- b = Ff(b, c, d, a, _x[15], 19);
- a = Gg(a, b, c, d, _x[0], 3);
- d = Gg(d, a, b, c, _x[4], 5);
- c = Gg(c, d, a, b, _x[8], 9);
- b = Gg(b, c, d, a, _x[12], 13);
- a = Gg(a, b, c, d, _x[1], 3);
- d = Gg(d, a, b, c, _x[5], 5);
- c = Gg(c, d, a, b, _x[9], 9);
- b = Gg(b, c, d, a, _x[13], 13);
- a = Gg(a, b, c, d, _x[2], 3);
- d = Gg(d, a, b, c, _x[6], 5);
- c = Gg(c, d, a, b, _x[10], 9);
- b = Gg(b, c, d, a, _x[14], 13);
- a = Gg(a, b, c, d, _x[3], 3);
- d = Gg(d, a, b, c, _x[7], 5);
- c = Gg(c, d, a, b, _x[11], 9);
- b = Gg(b, c, d, a, _x[15], 13);
- a = Hh(a, b, c, d, _x[0], 3);
- d = Hh(d, a, b, c, _x[8], 9);
- c = Hh(c, d, a, b, _x[4], 11);
- b = Hh(b, c, d, a, _x[12], 15);
- a = Hh(a, b, c, d, _x[2], 3);
- d = Hh(d, a, b, c, _x[10], 9);
- c = Hh(c, d, a, b, _x[6], 11);
- b = Hh(b, c, d, a, _x[14], 15);
- a = Hh(a, b, c, d, _x[1], 3);
- d = Hh(d, a, b, c, _x[9], 9);
- c = Hh(c, d, a, b, _x[5], 11);
- b = Hh(b, c, d, a, _x[13], 15);
- a = Hh(a, b, c, d, _x[3], 3);
- d = Hh(d, a, b, c, _x[11], 9);
- c = Hh(c, d, a, b, _x[7], 11);
- b = Hh(b, c, d, a, _x[15], 15);
- _context[0] += a;
- _context[1] += b;
- _context[2] += c;
- _context[3] += d;
- }
-
- // The basic MD4 atomic functions.
- private int Ff(int a, int b, int c, int d, int x, int s)
- {
- int t = a + ((b & c) | (~b & d)) + x;
- return t << s | (int)(((uint)t) >> (32 - s));
- }
-
- private int Gg(int a, int b, int c, int d, int x, int s)
- {
- int t = a + ((b & (c | d)) | (c & d)) + x + unchecked(0x5A827999);
- return t << s | (int)(((uint)t) >> (32 - s));
- }
-
- private int Hh(int a, int b, int c, int d, int x, int s)
- {
- int t = a + (b ^ c ^ d) + x + unchecked(0x6ED9EBA1);
- return t << s | (int)(((uint)t) >> (32 - s));
- }
-
- public override byte[] Digest()
- {
- return EngineDigest();
- }
-
- public override int GetDigestLength()
- {
- return EngineDigest().Length;
- }
-
- public override void Reset()
- {
- EngineReset();
- }
-
- public override void Update(byte[] b)
- {
- EngineUpdate(b, 0, b.Length);
- }
-
- public override void Update(byte b)
- {
- EngineUpdate(b);
- }
-
- public override void Update(byte[] b, int offset, int len)
- {
- EngineUpdate(b, offset, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs
deleted file mode 100644
index b17e076e7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Util
-{
- public class Rc4
- {
- internal byte[] S;
-
- internal int I;
-
- internal int J;
-
- public Rc4()
- {
- }
-
- public Rc4(byte[] key)
- {
- Init(key, 0, key.Length);
- }
-
- public virtual void Init(byte[] key, int ki, int klen)
- {
- S = new byte[256];
- for (I = 0; I < 256; I++)
- {
- S[I] = unchecked((byte)I);
- }
- for (I = J = 0; I < 256; I++)
- {
- J = (J + key[ki + I % klen] + S[I]) & unchecked(0xff);
- byte t = S[I];
- S[I] = S[J];
- S[J] = t;
- }
- I = J = 0;
- }
-
- public virtual void Update(byte[] src, int soff, int slen, byte[] dst, int doff)
- {
- int slim;
- slim = soff + slen;
- while (soff < slim)
- {
- I = (I + 1) & unchecked(0xff);
- J = (J + S[I]) & unchecked(0xff);
- byte t = S[I];
- S[I] = S[J];
- S[J] = t;
- dst[doff++] = unchecked((byte)(src[soff++] ^ S[(S[I] + S[J]) & unchecked(0xff)]));
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs
deleted file mode 100644
index 2868a840a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace SharpCifs.Util.Sharpen
-{
- public abstract class AbstractMap<T, TU> : IDictionary<T, TU>
- {
- public virtual void Clear ()
- {
- EntrySet ().Clear ();
- }
-
- public virtual bool ContainsKey (object name)
- {
- return EntrySet ().Any (p => p.Key.Equals ((T)name));
- }
-
- public abstract ICollection<KeyValuePair<T, TU>> EntrySet ();
-
- public virtual TU Get (object key)
- {
- return EntrySet ().Where (p => p.Key.Equals (key)).Select (p => p.Value).FirstOrDefault ();
- }
-
- protected virtual IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator ()
- {
- return EntrySet ().GetEnumerator ();
- }
-
- public virtual bool IsEmpty ()
- {
- return !EntrySet ().Any ();
- }
-
- public virtual TU Put (T key, TU value)
- {
- throw new NotSupportedException ();
- }
-
- public virtual TU Remove (object key)
- {
- Iterator<TU> iterator = EntrySet () as Iterator<TU>;
- if (iterator == null) {
- throw new NotSupportedException ();
- }
- while (iterator.HasNext ()) {
- TU local = iterator.Next ();
- if (local.Equals ((T)key)) {
- iterator.Remove ();
- return local;
- }
- }
- return default(TU);
- }
-
- void ICollection<KeyValuePair<T, TU>>.Add (KeyValuePair<T, TU> item)
- {
- Put (item.Key, item.Value);
- }
-
- bool ICollection<KeyValuePair<T, TU>>.Contains (KeyValuePair<T, TU> item)
- {
- throw new NotImplementedException ();
- }
-
- void ICollection<KeyValuePair<T, TU>>.CopyTo (KeyValuePair<T, TU>[] array, int arrayIndex)
- {
- EntrySet ().CopyTo (array, arrayIndex);
- }
-
- bool ICollection<KeyValuePair<T, TU>>.Remove (KeyValuePair<T, TU> item)
- {
- Remove (item.Key);
- return true;
- }
-
- void IDictionary<T, TU>.Add (T key, TU value)
- {
- Put (key, value);
- }
-
- bool IDictionary<T, TU>.ContainsKey (T key)
- {
- return ContainsKey (key);
- }
-
- bool IDictionary<T, TU>.Remove (T key)
- {
- if (ContainsKey (key)) {
- Remove (key);
- return true;
- }
- return false;
- }
-
- bool IDictionary<T, TU>.TryGetValue (T key, out TU value)
- {
- if (ContainsKey (key)) {
- value = Get (key);
- return true;
- }
- value = default(TU);
- return false;
- }
-
- IEnumerator<KeyValuePair<T, TU>> IEnumerable<KeyValuePair<T, TU>>.GetEnumerator ()
- {
- return InternalGetEnumerator ();
- }
-
- IEnumerator IEnumerable.GetEnumerator ()
- {
- return InternalGetEnumerator ();
- }
-
- public virtual int Count {
- get { return EntrySet ().Count; }
- }
-
- public TU this[T key] {
- get { return Get (key); }
- set { Put (key, value); }
- }
-
- public virtual IEnumerable<T> Keys {
- get { return EntrySet ().Select (p => p.Key); }
- }
-
- int ICollection<KeyValuePair<T, TU>>.Count {
- get { return Count; }
- }
-
- bool ICollection<KeyValuePair<T, TU>>.IsReadOnly {
- get { return false; }
- }
-
- ICollection<T> IDictionary<T, TU>.Keys {
- get { return Keys.ToList (); }
- }
-
- ICollection<TU> IDictionary<T, TU>.Values {
- get { return Values.ToList (); }
- }
-
- public virtual IEnumerable<TU> Values {
- get { return EntrySet ().Select (p => p.Value); }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs
deleted file mode 100644
index b3a0a85fa..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class Arrays
- {
- public static List<T> AsList<T> (params T[] array)
- {
- return array.ToList ();
- }
-
- public static bool Equals<T> (T[] a1, T[] a2)
- {
- if (a1.Length != a2.Length) {
- return false;
- }
- return !a1.Where((t, i) => !t.Equals(a2[i])).Any();
- }
-
- public static void Fill<T> (T[] array, T val)
- {
- Fill (array, 0, array.Length, val);
- }
-
- public static void Fill<T> (T[] array, int start, int end, T val)
- {
- for (int i = start; i < end; i++) {
- array[i] = val;
- }
- }
-
- public static void Sort (string[] array)
- {
- Array.Sort (array, (s1,s2) => string.CompareOrdinal (s1,s2));
- }
-
- public static void Sort<T> (T[] array)
- {
- Array.Sort (array);
- }
-
- public static void Sort<T> (T[] array, IComparer<T> c)
- {
- Array.Sort (array, c);
- }
-
- public static void Sort<T> (T[] array, int start, int count)
- {
- Array.Sort (array, start, count);
- }
-
- public static void Sort<T> (T[] array, int start, int count, IComparer<T> c)
- {
- Array.Sort (array, start, count, c);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs
deleted file mode 100644
index b3824b0d2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class BufferedReader : StreamReader
- {
- public BufferedReader (InputStreamReader r) : base(r.BaseStream)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs
deleted file mode 100644
index 64a45915a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-//
-// BufferedWriter.cs
-//
-// Author:
-// Lluis Sanchez Gual <lluis@novell.com>
-//
-// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class BufferedWriter
- {
- StreamWriter _writer;
-
- public BufferedWriter (StreamWriter w)
- {
- _writer = w;
- }
-
- public void Write (string s)
- {
- _writer.Write (s);
- }
-
- public void NewLine ()
- {
- _writer.WriteLine ();
- }
-
- public void Close ()
- {
- //Stream.`Close` method deleted
- //_writer.Close ();
- _writer.Dispose();
- }
- }
-}
-
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs
deleted file mode 100644
index 76ca2dc95..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal class CharBuffer : CharSequence
- {
- internal string Wrapped;
-
- public override string ToString ()
- {
- return Wrapped;
- }
-
- public static CharBuffer Wrap (string str)
- {
- CharBuffer buffer = new CharBuffer ();
- buffer.Wrapped = str;
- return buffer;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs
deleted file mode 100644
index fa2acf7bd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System.Text;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class CharSequence
- {
- public static implicit operator CharSequence (string str)
- {
- return new StringCharSequence (str);
- }
-
- public static implicit operator CharSequence (StringBuilder str)
- {
- return new StringCharSequence (str.ToString ());
- }
- }
-
- class StringCharSequence: CharSequence
- {
- string _str;
-
- public StringCharSequence (string str)
- {
- this._str = str;
- }
-
- public override string ToString ()
- {
- return _str;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs
deleted file mode 100644
index 8560a2dc2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-
-// TODO: @bond Remove
-namespace SharpCifs.Util.Sharpen
-{
- internal static class Collections<T>
- {
- static readonly IList<T> Empty = new T [0];
- public static IList<T> EmptySet {
- get { return Empty; }
- }
-
- }
-
- public static class Collections
- {
- public static bool AddAll<T> (ICollection<T> list, IEnumerable toAdd)
- {
- foreach (T t in toAdd)
- list.Add (t);
- return true;
- }
-
- public static TV Remove<TK, TV> (IDictionary<TK, TV> map, TK toRemove) where TK : class
- {
- TV local;
- if (map.TryGetValue (toRemove, out local)) {
- map.Remove (toRemove);
- return local;
- }
- return default(TV);
- }
-
-
- public static T[] ToArray<T> (ICollection<T> list)
- {
- T[] array = new T[list.Count];
- list.CopyTo (array, 0);
- return array;
- }
-
- public static T[] ToArray<T>(List<object> list)
- {
- T[] array = new T[list.Count];
- for(int c = 0; c < list.Count; c++)
- {
- array[c] = (T)list[c];
- }
-
- return array;
- }
-
-
- public static TU[] ToArray<T,TU> (ICollection<T> list, TU[] res) where T:TU
- {
- if (res.Length < list.Count)
- res = new TU [list.Count];
-
- int n = 0;
- foreach (T t in list)
- res [n++] = t;
-
- if (res.Length > list.Count)
- res [list.Count] = default (T);
- return res;
- }
-
- public static IDictionary<TK,TV> EmptyMap<TK,TV> ()
- {
- return new Dictionary<TK,TV> ();
- }
-
- public static IList<T> EmptyList<T> ()
- {
- return Collections<T>.EmptySet;
- }
-
- public static ICollection<T> EmptySet<T> ()
- {
- return Collections<T>.EmptySet;
- }
-
- public static IList<T> NCopies<T> (int n, T elem)
- {
- List<T> list = new List<T> (n);
- while (n-- > 0) {
- list.Add (elem);
- }
- return list;
- }
-
- public static void Reverse<T> (IList<T> list)
- {
- int end = list.Count - 1;
- int index = 0;
- while (index < end) {
- T tmp = list [index];
- list [index] = list [end];
- list [end] = tmp;
- ++index;
- --end;
- }
- }
-
- public static ICollection<T> Singleton<T> (T item)
- {
- List<T> list = new List<T> (1);
- list.Add (item);
- return list;
- }
-
- public static IList<T> SingletonList<T> (T item)
- {
- List<T> list = new List<T> (1);
- list.Add (item);
- return list;
- }
-
- public static IList<T> SynchronizedList<T> (IList<T> list)
- {
- return new SynchronizedList<T> (list);
- }
-
- public static ICollection<T> UnmodifiableCollection<T> (ICollection<T> list)
- {
- return list;
- }
-
- public static IList<T> UnmodifiableList<T> (IList<T> list)
- {
- return new ReadOnlyCollection<T> (list);
- }
-
- public static ICollection<T> UnmodifiableSet<T> (ICollection<T> list)
- {
- return list;
- }
-
- public static IDictionary<TK,TV> UnmodifiableMap<TK,TV> (IDictionary<TK,TV> dict)
- {
- return dict;
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs
deleted file mode 100644
index 7f464ad36..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class ConcurrentHashMap<T, TU> : AbstractMap<T, TU>, IConcurrentMap<T, TU>
- {
- private Dictionary<T, TU> _table;
-
- public ConcurrentHashMap ()
- {
- _table = new Dictionary<T, TU> ();
- }
-
- public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel)
- {
- _table = new Dictionary<T, TU> (initialCapacity);
- }
-
- public override void Clear ()
- {
- lock (_table) {
- _table = new Dictionary<T, TU> ();
- }
- }
-
- public override bool ContainsKey (object name)
- {
- return _table.ContainsKey ((T)name);
- }
-
- public override ICollection<KeyValuePair<T, TU>> EntrySet ()
- {
- return this;
- }
-
- public override TU Get (object key)
- {
- TU local;
- _table.TryGetValue ((T)key, out local);
- return local;
- }
-
- protected override IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator ()
- {
- return _table.GetEnumerator ();
- }
-
- public override bool IsEmpty ()
- {
- return _table.Count == 0;
- }
-
- public override TU Put (T key, TU value)
- {
- lock (_table) {
- TU old = Get (key);
- Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table);
- newTable[key] = value;
- _table = newTable;
- return old;
- }
- }
-
- public TU PutIfAbsent (T key, TU value)
- {
- lock (_table) {
- if (!ContainsKey (key)) {
- Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table);
- newTable[key] = value;
- _table = newTable;
- return value;
- }
- return Get (key);
- }
- }
-
- public override TU Remove (object key)
- {
- lock (_table) {
- TU old = Get ((T)key);
- Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table);
- newTable.Remove ((T)key);
- _table = newTable;
- return old;
- }
- }
-
- public bool Remove (object key, object value)
- {
- lock (_table) {
- if (ContainsKey (key) && value.Equals (Get (key))) {
- Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table);
- newTable.Remove ((T)key);
- _table = newTable;
- return true;
- }
- return false;
- }
- }
-
- public bool Replace (T key, TU oldValue, TU newValue)
- {
- lock (_table) {
- if (ContainsKey (key) && oldValue.Equals (Get (key))) {
- Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table);
- newTable[key] = newValue;
- _table = newTable;
- return true;
- }
- return false;
- }
- }
-
- public override IEnumerable<T> Keys {
- get { return _table.Keys; }
- }
-
- public override IEnumerable<TU> Values {
- get { return _table.Values; }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs
deleted file mode 100644
index 9a3b7ec4a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using System;
-using System.Globalization;
-
-namespace SharpCifs.Util.Sharpen
-{
- public abstract class DateFormat
- {
- public const int Default = 2;
-
- public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle)
- {
- return GetDateTimeInstance (dateStyle, timeStyle, CultureInfo.CurrentCulture);
- }
-
- public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle, CultureInfo aLocale)
- {
- return new SimpleDateFormat (aLocale.DateTimeFormat.FullDateTimePattern, aLocale);
- }
-
- TimeZoneInfo _timeZone;
-
- public abstract DateTime Parse (string value);
-
- public TimeZoneInfo GetTimeZone ()
- {
- return _timeZone;
- }
-
- public void SetTimeZone (TimeZoneInfo timeZone)
- {
- this._timeZone = timeZone;
- }
-
- public abstract string Format (DateTime time);
- }
-}
-
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs
deleted file mode 100644
index f8efdde2a..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class EnumeratorWrapper<T> : Iterator<T>
- {
- object _collection;
- IEnumerator<T> _e;
- T _lastVal;
- bool _more;
- bool _copied;
-
- public EnumeratorWrapper (object collection, IEnumerator<T> e)
- {
- this._e = e;
- this._collection = collection;
- _more = e.MoveNext ();
- }
-
- public override bool HasNext ()
- {
- return _more;
- }
-
- public override T Next ()
- {
- if (!_more)
- throw new NoSuchElementException ();
- _lastVal = _e.Current;
- _more = _e.MoveNext ();
- return _lastVal;
- }
-
- public override void Remove ()
- {
- ICollection<T> col = _collection as ICollection<T>;
- if (col == null) {
- throw new NotSupportedException ();
- }
- if (_more && !_copied) {
- // Read the remaining elements, since the current enumerator
- // will be invalid after removing the element
- List<T> remaining = new List<T> ();
- do {
- remaining.Add (_e.Current);
- } while (_e.MoveNext ());
- _e = remaining.GetEnumerator ();
- _e.MoveNext ();
- _copied = true;
- }
- col.Remove (_lastVal);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs
deleted file mode 100644
index ec88b2849..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs
+++ /dev/null
@@ -1,217 +0,0 @@
-//
-// Exceptions.cs
-//
-// Author:
-// Lluis Sanchez Gual <lluis@novell.com>
-//
-// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class VirtualMachineError : Error
- {
- }
-
- public class StackOverflowError : VirtualMachineError
- {
- }
-
- public class BrokenBarrierException : Exception
- {
- }
-
- internal class BufferUnderflowException : Exception
- {
- }
-
- public class CharacterCodingException : Exception
- {
- }
-
- public class DataFormatException : Exception
- {
- }
-
- public class EofException : Exception
- {
- public EofException ()
- {
- }
-
- public EofException (string msg) : base(msg)
- {
- }
- }
-
- public class Error : Exception
- {
- public Error ()
- {
- }
-
- public Error (Exception ex) : base("Runtime Exception", ex)
- {
- }
-
- public Error (string msg) : base(msg)
- {
- }
-
- public Error (string msg, Exception ex) : base(msg, ex)
- {
- }
- }
-
- public class ExecutionException : Exception
- {
- public ExecutionException (Exception inner): base ("Execution failed", inner)
- {
- }
- }
-
- public class InstantiationException : Exception
- {
- }
-
- public class InterruptedIoException : Exception
- {
- public InterruptedIoException (string msg) : base(msg)
- {
- }
- }
-
- public class MissingResourceException : Exception
- {
- }
-
- public class NoSuchAlgorithmException : Exception
- {
- }
-
- public class NoSuchElementException : Exception
- {
- }
-
- internal class NoSuchMethodException : Exception
- {
- }
-
- internal class OverlappingFileLockException : Exception
- {
- }
-
- public class ParseException : Exception
- {
- public ParseException ()
- {
- }
-
- public ParseException (string msg, int errorOffset) : base(string.Format ("Msg: {0}. Error Offset: {1}", msg, errorOffset))
- {
- }
- }
-
- public class RuntimeException : Exception
- {
- public RuntimeException ()
- {
- }
-
- public RuntimeException (Exception ex) : base("Runtime Exception", ex)
- {
- }
-
- public RuntimeException (string msg) : base(msg)
- {
- }
-
- public RuntimeException (string msg, Exception ex) : base(msg, ex)
- {
- }
- }
-
- internal class StringIndexOutOfBoundsException : Exception
- {
- }
-
- public class UnknownHostException : Exception
- {
- public UnknownHostException ()
- {
- }
-
- public UnknownHostException(string message) : base(message)
- {
-
- }
-
- public UnknownHostException (Exception ex): base ("Host not found", ex)
- {
- }
- }
-
- public class UnsupportedEncodingException : Exception
- {
- }
-
- internal class UriSyntaxException : Exception
- {
- public UriSyntaxException (string s, string msg) : base(s + " " + msg)
- {
- }
- }
-
- internal class ZipException : Exception
- {
- }
-
- public class GitException : Exception
- {
- }
-
- public class ConnectException: Exception
- {
- public ConnectException (string msg): base (msg)
- {
- }
- }
-
- class KeyManagementException: Exception
- {
- }
-
- class IllegalCharsetNameException: Exception
- {
- public IllegalCharsetNameException (string msg): base (msg)
- {
- }
- }
-
- class UnsupportedCharsetException: Exception
- {
- public UnsupportedCharsetException (string msg): base (msg)
- {
- }
- }
-}
-
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs
deleted file mode 100644
index 1716adef7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs
+++ /dev/null
@@ -1,696 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Reflection;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Threading.Tasks;
-//using Windows.Networking;
-//using Windows.Networking.Sockets;
-
-namespace SharpCifs.Util.Sharpen
-{
-
-
- public static class Extensions
- {
- private static readonly long EpochTicks;
-
- static Extensions()
- {
- DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- EpochTicks = time.Ticks;
- }
-
- public static void Add<T>(this IList<T> list, int index, T item)
- {
- list.Insert(index, item);
- }
-
- public static void AddFirst<T>(this IList<T> list, T item)
- {
- list.Insert(0, item);
- }
-
- public static void AddLast<T>(this IList<T> list, T item)
- {
- list.Add(item);
- }
-
- public static void RemoveLast<T>(this IList<T> list)
- {
- if (list.Count > 0)
- list.Remove(list.Count - 1);
- }
-
- public static StringBuilder AppendRange(this StringBuilder sb, string str, int start, int end)
- {
- return sb.Append(str, start, end - start);
- }
-
- public static StringBuilder Delete(this StringBuilder sb, int start, int end)
- {
- return sb.Remove(start, end - start);
- }
-
- public static void SetCharAt(this StringBuilder sb, int index, char c)
- {
- sb[index] = c;
- }
-
- public static int IndexOf(this StringBuilder sb, string str)
- {
- return sb.ToString().IndexOf(str);
- }
-
- public static int BitCount(int val)
- {
- uint num = (uint)val;
- int count = 0;
- for (int i = 0; i < 32; i++)
- {
- if ((num & 1) != 0)
- {
- count++;
- }
- num >>= 1;
- }
- return count;
- }
-
- public static IndexOutOfRangeException CreateIndexOutOfRangeException(int index)
- {
- return new IndexOutOfRangeException("Index: " + index);
- }
-
- public static string Decode(this Encoding e, byte[] chars, int start, int len)
- {
- try
- {
- byte[] bom = e.GetPreamble();
- if (bom != null && bom.Length > 0)
- {
- if (len >= bom.Length)
- {
- int pos = start;
- bool hasBom = true;
- for (int n = 0; n < bom.Length && hasBom; n++)
- {
- if (bom[n] != chars[pos++])
- hasBom = false;
- }
- if (hasBom)
- {
- len -= pos - start;
- start = pos;
- }
- }
- }
- return e.GetString(chars, start, len);
- }
- catch (DecoderFallbackException)
- {
- throw new CharacterCodingException();
- }
- }
-
-
-
- public static Encoding GetEncoding(string name)
- {
- // Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
- try
- {
-
- Encoding e = Encoding.GetEncoding(name.Replace('_', '-'));
- if (e is UTF8Encoding)
- return new UTF8Encoding(false, true);
-
- return e;
- }
- catch (ArgumentException)
- {
- throw new UnsupportedCharsetException(name);
- }
- }
-
- public static ICollection<KeyValuePair<T, TU>> EntrySet<T, TU>(this IDictionary<T, TU> s)
- {
- return s;
- }
-
-
- public static bool AddItem<T>(this IList<T> list, T item)
- {
- list.Add(item);
- return true;
- }
-
- public static bool AddItem<T>(this ICollection<T> list, T item)
- {
- list.Add(item);
- return true;
- }
-
- public static TU Get<T, TU>(this IDictionary<T, TU> d, T key)
- {
- TU val;
- d.TryGetValue(key, out val);
- return val;
- }
-
-
- public static TU Put<T, TU>(this IDictionary<T, TU> d, T key, TU value)
- {
- TU old;
- d.TryGetValue(key, out old);
- d[key] = value;
- return old;
- }
-
- public static void PutAll<T, TU>(this IDictionary<T, TU> d, IDictionary<T, TU> values)
- {
- foreach (KeyValuePair<T, TU> val in values)
- d[val.Key] = val.Value;
- }
-
-
- public static CultureInfo GetEnglishCulture()
- {
- return new CultureInfo("en-US");
- }
-
- public static T GetFirst<T>(this IList<T> list)
- {
- return ((list.Count == 0) ? default(T) : list[0]);
- }
-
- public static CultureInfo GetGermanCulture()
- {
- CultureInfo r = new CultureInfo("de-DE");
- return r;
- }
-
- public static T GetLast<T>(this IList<T> list)
- {
- return ((list.Count == 0) ? default(T) : list[list.Count - 1]);
- }
-
- public static int GetOffset(this TimeZoneInfo tzone, long date)
- {
- return (int)tzone.GetUtcOffset(MillisToDateTimeOffset(date, 0).DateTime).TotalMilliseconds;
- }
-
- public static long GetTime(this DateTime dateTime)
- {
- return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
- }
-
- public static void InitCause(this Exception ex, Exception cause)
- {
- Console.WriteLine(cause);
- }
-
- public static bool IsEmpty<T>(this ICollection<T> col)
- {
- return (col.Count == 0);
- }
-
- public static bool IsEmpty<T>(this Stack<T> col)
- {
- return (col.Count == 0);
- }
-
- public static bool IsLower(this char c)
- {
- return char.IsLower(c);
- }
-
- public static bool IsUpper(this char c)
- {
- return char.IsUpper(c);
- }
-
- public static Iterator<T> Iterator<T>(this ICollection<T> col)
- {
- return new EnumeratorWrapper<T>(col, col.GetEnumerator());
- }
-
- public static Iterator<T> Iterator<T>(this IEnumerable<T> col)
- {
- return new EnumeratorWrapper<T>(col, col.GetEnumerator());
- }
-
- public static T Last<T>(this ICollection<T> col)
- {
- IList<T> list = col as IList<T>;
- if (list != null)
- {
- return list[list.Count - 1];
- }
- return col.Last();
- }
-
- public static int LowestOneBit(int val)
- {
- return (1 << NumberOfTrailingZeros(val));
- }
-
- public static bool Matches(this string str, string regex)
- {
- Regex regex2 = new Regex(regex);
- return regex2.IsMatch(str);
- }
-
- public static DateTime CreateDate(long milliSecondsSinceEpoch)
- {
- long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
- return new DateTime(num);
- }
-
- public static DateTime CreateDateFromUTC(long milliSecondsSinceEpoch)
- {
- long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
- return new DateTime(num, DateTimeKind.Utc);
- }
-
-
- public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, long offsetMinutes)
- {
- TimeSpan offset = TimeSpan.FromMinutes(offsetMinutes);
- long num = EpochTicks + (milliSecondsSinceEpoch * 10000);
- return new DateTimeOffset(num + offset.Ticks, offset);
- }
-
- public static int NumberOfLeadingZeros(int val)
- {
- uint num = (uint)val;
- int count = 0;
- while ((num & 0x80000000) == 0)
- {
- num = num << 1;
- count++;
- }
- return count;
- }
-
- public static int NumberOfTrailingZeros(int val)
- {
- uint num = (uint)val;
- int count = 0;
- while ((num & 1) == 0)
- {
- num = num >> 1;
- count++;
- }
- return count;
- }
-
- public static int Read(this StreamReader reader, char[] data)
- {
- return reader.Read(data, 0, data.Length);
- }
-
- public static T Remove<T>(this IList<T> list, T item)
- {
- int index = list.IndexOf(item);
- if (index == -1)
- {
- return default(T);
- }
- T local = list[index];
- list.RemoveAt(index);
- return local;
- }
-
- public static T Remove<T>(this IList<T> list, int i)
- {
- T old;
- try
- {
- old = list[i];
- list.RemoveAt(i);
- }
- catch (IndexOutOfRangeException)
- {
- throw new NoSuchElementException();
- }
- return old;
- }
-
- public static T RemoveFirst<T>(this IList<T> list)
- {
- return list.Remove(0);
- }
-
- public static string ReplaceAll(this string str, string regex, string replacement)
- {
- Regex rgx = new Regex(regex);
-
- if (replacement.IndexOfAny(new[] { '\\', '$' }) != -1)
- {
- // Back references not yet supported
- StringBuilder sb = new StringBuilder();
- for (int n = 0; n < replacement.Length; n++)
- {
- char c = replacement[n];
- if (c == '$')
- throw new NotSupportedException("Back references not supported");
- if (c == '\\')
- c = replacement[++n];
- sb.Append(c);
- }
- replacement = sb.ToString();
- }
-
- return rgx.Replace(str, replacement);
- }
-
- public static bool RegionMatches(this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len)
- {
- if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length)
- return false;
- return string.Compare(str, toOffset, other, ooffset, len) == 0;
- }
-
- public static T Set<T>(this IList<T> list, int index, T item)
- {
- T old = list[index];
- list[index] = item;
- return old;
- }
-
- public static int Signum(long val)
- {
- if (val < 0)
- {
- return -1;
- }
- if (val > 0)
- {
- return 1;
- }
- return 0;
- }
-
- public static void RemoveAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
- {
- foreach (var u in items)
- col.Remove(u);
- }
-
- public static bool ContainsAll<T, TU>(this ICollection<T> col, ICollection<TU> items) where TU : T
- {
- foreach (var u in items)
- if (!col.Any(n => (ReferenceEquals(n, u)) || n.Equals(u)))
- return false;
- return true;
- }
-
- public static bool Contains<T>(this ICollection<T> col, object item)
- {
- if (!(item is T))
- return false;
- return col.Any(n => (ReferenceEquals(n, item)) || n.Equals(item));
- }
-
- public static void Sort<T>(this IList<T> list)
- {
- List<T> sorted = new List<T>(list);
- sorted.Sort();
- for (int i = 0; i < list.Count; i++)
- {
- list[i] = sorted[i];
- }
- }
-
- public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
- {
- List<T> sorted = new List<T>(list);
- sorted.Sort(comparer);
- for (int i = 0; i < list.Count; i++)
- {
- list[i] = sorted[i];
- }
- }
-
- public static string[] Split(this string str, string regex)
- {
- return str.Split(regex, 0);
- }
-
- public static string[] Split(this string str, string regex, int limit)
- {
- Regex rgx = new Regex(regex);
- List<string> list = new List<string>();
- int startIndex = 0;
- if (limit != 1)
- {
- int nm = 1;
- foreach (Match match in rgx.Matches(str))
- {
- list.Add(str.Substring(startIndex, match.Index - startIndex));
- startIndex = match.Index + match.Length;
- if (limit > 0 && ++nm == limit)
- break;
- }
- }
- if (startIndex < str.Length)
- {
- list.Add(str.Substring(startIndex));
- }
- if (limit >= 0)
- {
- int count = list.Count - 1;
- while ((count >= 0) && (list[count].Length == 0))
- {
- count--;
- }
- list.RemoveRange(count + 1, (list.Count - count) - 1);
- }
- return list.ToArray();
- }
-
- public static IList<T> SubList<T>(this IList<T> list, int start, int len)
- {
- List<T> sublist = new List<T>(len);
- for (int i = start; i < (start + len); i++)
- {
- sublist.Add(list[i]);
- }
- return sublist;
- }
-
- public static char[] ToCharArray(this string str)
- {
- char[] destination = new char[str.Length];
- str.CopyTo(0, destination, 0, str.Length);
- return destination;
- }
-
- public static long ToMillisecondsSinceEpoch(this DateTime dateTime)
- {
- if (dateTime.Kind != DateTimeKind.Utc)
- {
- throw new ArgumentException("dateTime is expected to be expressed as a UTC DateTime", "dateTime");
- }
- return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch();
- }
-
- public static long ToMillisecondsSinceEpoch(this DateTimeOffset dateTimeOffset)
- {
- return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) / TimeSpan.TicksPerMillisecond);
- }
-
- public static string ToOctalString(int val)
- {
- return Convert.ToString(val, 8);
- }
-
- public static string ToHexString(int val)
- {
- return Convert.ToString(val, 16);
- }
-
- public static string ToString(object val)
- {
- return val.ToString();
- }
-
- public static string ToString(int val, int bas)
- {
- return Convert.ToString(val, bas);
- }
-
- public static IList<TU> UpcastTo<T, TU>(this IList<T> s) where T : TU
- {
- List<TU> list = new List<TU>(s.Count);
- for (int i = 0; i < s.Count; i++)
- {
- list.Add(s[i]);
- }
- return list;
- }
-
- public static ICollection<TU> UpcastTo<T, TU>(this ICollection<T> s) where T : TU
- {
- List<TU> list = new List<TU>(s.Count);
- foreach (var v in s)
- {
- list.Add(v);
- }
- return list;
- }
-
- public static T ValueOf<T>(T val)
- {
- return val;
- }
-
-
- //use? for NUnit-testing?
- //public static string GetTestName(object obj)
- //{
- // return GetTestName();
- //}
-
- //public static string GetTestName()
- //{
- // MethodBase met;
- // int n = 0;
- // do
- // {
- // met = new StackFrame(n).GetMethod();
- // if (met != null)
- // {
- // foreach (Attribute at in met.GetCustomAttributes(true))
- // {
- // if (at.GetType().FullName == "NUnit.Framework.TestAttribute")
- // {
- // // Convert back to camel case
- // string name = met.Name;
- // if (char.IsUpper(name[0]))
- // name = char.ToLower(name[0]) + name.Substring(1);
- // return name;
- // }
- // }
- // }
- // n++;
- // } while (met != null);
- // return "";
- //}
-
- public static string GetHostAddress(this IPAddress addr)
- {
- return addr.ToString();
- }
-
-
- public static IPAddress GetAddressByName(string host)
- {
- if (host == "0.0.0.0")
- {
- return IPAddress.Any;
- }
-
- try
- {
- return IPAddress.Parse(host);
- }
- catch (Exception ex)
- {
- return null;
- }
- }
-
- public static IPAddress[] GetAddressesByName(string host)
- {
- //IReadOnlyList<EndpointPair> data = null;
-
- //try
- //{
- // Task.Run(async () =>
- // {
- // data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0");
- // }).Wait();
- //}
- //catch (Exception ex)
- //{
- // return null;
- //}
-
- //return data != null
- // ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4)
- // .GroupBy(i => i.RemoteHostName.DisplayName)
- // .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName))
- // .ToArray()
- // : null;
-
- //get v4-address only
- var entry = Task.Run(() => System.Net.Dns.GetHostEntryAsync(host))
- .GetAwaiter()
- .GetResult();
- return entry.AddressList
- .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)
- .ToArray();
-
- }
-
- public static string GetImplementationVersion(this Assembly asm)
- {
- return asm.GetName().Version.ToString();
- }
-
- public static string GetHost(this Uri uri)
- {
- return string.IsNullOrEmpty(uri.Host) ? "" : uri.Host;
- }
-
- public static string GetUserInfo(this Uri uri)
- {
- return string.IsNullOrEmpty(uri.UserInfo) ? null : uri.UserInfo;
- }
-
- public static string GetQuery(this Uri uri)
- {
- return string.IsNullOrEmpty(uri.Query) ? null : uri.Query;
- }
-
- public static int GetLocalPort(this Socket socket)
- {
- return ((IPEndPoint)socket.LocalEndPoint).Port;
- }
-
- public static int GetPort(this Socket socket)
- {
- return ((IPEndPoint)socket.RemoteEndPoint).Port;
- }
-
- public static IPAddress GetInetAddress(this Socket socket)
- {
- return ((IPEndPoint)socket.RemoteEndPoint).Address;
- }
-
-
- /*public static bool RemoveElement(this ArrayList list, object elem)
- {
- int i = list.IndexOf(elem);
- if (i == -1)
- return false;
- list.RemoveAt(i);
- return true;
- }*/
-
- public static Semaphore CreateSemaphore(int count)
- {
- return new Semaphore(count, int.MaxValue);
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs
deleted file mode 100644
index 25c5e06e0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class FileInputStream : InputStream
- {
- public FileInputStream (FilePath file) : this(file.GetPath ())
- {
- }
-
- public FileInputStream (string file)
- {
- if (!File.Exists (file)) {
- throw new FileNotFoundException ("File not found", file);
- }
- Wrapped = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs
deleted file mode 100644
index bf8029488..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class FileOutputStream : OutputStream
- {
- public FileOutputStream (FilePath file): this (file.GetPath (), false)
- {
- }
-
- public FileOutputStream (string file): this (file, false)
- {
- }
-
- public FileOutputStream (FilePath file, bool append) : this(file.GetPath (), append)
- {
- }
-
- public FileOutputStream (string file, bool append)
- {
- try {
- if (append) {
- Wrapped = File.Open (file, FileMode.Append, FileAccess.Write);
- } else {
- Wrapped = File.Open (file, FileMode.Create, FileAccess.Write);
- }
- } catch (DirectoryNotFoundException) {
- throw new FileNotFoundException ("File not found: " + file);
- }
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs
deleted file mode 100644
index 1b2f5eddc..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs
+++ /dev/null
@@ -1,313 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class FilePath
- {
- private string _path;
- private static long _tempCounter;
-
- public FilePath ()
- {
- }
-
- public FilePath (string path)
- : this ((string) null, path)
- {
-
- }
-
- public FilePath (FilePath other, string child)
- : this ((string) other, child)
- {
-
- }
-
- public FilePath (string other, string child)
- {
- if (other == null) {
- _path = child;
- } else {
- while (!string.IsNullOrEmpty(child) && (child[0] == Path.DirectorySeparatorChar || child[0] == Path.AltDirectorySeparatorChar))
- child = child.Substring (1);
-
- if (!string.IsNullOrEmpty(other) && other[other.Length - 1] == Path.VolumeSeparatorChar)
- other += Path.DirectorySeparatorChar;
-
- _path = Path.Combine (other, child);
- }
- }
-
- public static implicit operator FilePath (string name)
- {
- return new FilePath (name);
- }
-
- public static implicit operator string (FilePath filePath)
- {
- return filePath == null ? null : filePath._path;
- }
-
- public override bool Equals (object obj)
- {
- FilePath other = obj as FilePath;
- if (other == null)
- return false;
- return GetCanonicalPath () == other.GetCanonicalPath ();
- }
-
- public override int GetHashCode ()
- {
- return _path.GetHashCode ();
- }
-
- public bool CreateNewFile ()
- {
- try {
- //Stream.`Close` method deleted
- //File.Open (_path, FileMode.CreateNew).Close ();
- File.Open(_path, FileMode.CreateNew).Dispose();
- return true;
- } catch {
- return false;
- }
- }
-
- public static FilePath CreateTempFile ()
- {
- return new FilePath (Path.GetTempFileName ());
- }
-
- public static FilePath CreateTempFile (string prefix, string suffix)
- {
- return CreateTempFile (prefix, suffix, null);
- }
-
- public static FilePath CreateTempFile (string prefix, string suffix, FilePath directory)
- {
- string file;
- if (prefix == null) {
- throw new ArgumentNullException ("prefix");
- }
- if (prefix.Length < 3) {
- throw new ArgumentException ("prefix must have at least 3 characters");
- }
- string str = (directory == null) ? Path.GetTempPath () : directory.GetPath ();
- do {
- file = Path.Combine (str, prefix + Interlocked.Increment (ref _tempCounter) + suffix);
- } while (File.Exists (file));
-
- new FileOutputStream (file).Close ();
- return new FilePath (file);
- }
-
-
- public void DeleteOnExit ()
- {
- }
-
-
- public FilePath GetAbsoluteFile ()
- {
- return new FilePath (Path.GetFullPath (_path));
- }
-
- public string GetAbsolutePath ()
- {
- return Path.GetFullPath (_path);
- }
-
- public FilePath GetCanonicalFile ()
- {
- return new FilePath (GetCanonicalPath ());
- }
-
- public string GetCanonicalPath ()
- {
- string p = Path.GetFullPath (_path);
- p.TrimEnd (Path.DirectorySeparatorChar);
- return p;
- }
-
- public string GetName ()
- {
- return Path.GetFileName (_path);
- }
-
- public FilePath GetParentFile ()
- {
- return new FilePath (Path.GetDirectoryName (_path));
- }
-
- public string GetPath ()
- {
- return _path;
- }
-
- public bool IsAbsolute ()
- {
- return Path.IsPathRooted (_path);
- }
-
- public bool IsDirectory ()
- {
- return false; // FileHelper.Instance.IsDirectory(this);
- }
-
- public bool IsFile ()
- {
- return false; //FileHelper.Instance.IsFile (this);
- }
-
- public long LastModified ()
- {
- return 0; // FileHelper.Instance.LastModified(this);
- }
-
- public long Length ()
- {
- return 0; // FileHelper.Instance.Length(this);
- }
-
- public string[] List ()
- {
- return List (null);
- }
-
- public string[] List (IFilenameFilter filter)
- {
- try {
- if (IsFile ())
- return null;
- List<string> list = new List<string> ();
- foreach (string filePth in Directory.GetFileSystemEntries (_path)) {
- string fileName = Path.GetFileName (filePth);
- if ((filter == null) || filter.Accept (this, fileName)) {
- list.Add (fileName);
- }
- }
- return list.ToArray ();
- } catch {
- return null;
- }
- }
-
- public FilePath[] ListFiles ()
- {
- try {
- if (IsFile ())
- return null;
- List<FilePath> list = new List<FilePath> ();
- foreach (string filePath in Directory.GetFileSystemEntries (_path)) {
- list.Add (new FilePath (filePath));
- }
- return list.ToArray ();
- } catch {
- return null;
- }
- }
-
- static void MakeDirWritable (string dir)
- {
- //FileHelper.Instance.MakeDirWritable (dir);
- }
-
- static void MakeFileWritable (string file)
- {
- //FileHelper.Instance.MakeFileWritable (file);
- }
-
- public bool Mkdir ()
- {
- try {
- if (Directory.Exists (_path))
- return false;
- Directory.CreateDirectory (_path);
- return true;
- } catch (Exception) {
- return false;
- }
- }
-
- public bool Mkdirs ()
- {
- try {
- if (Directory.Exists (_path))
- return false;
- Directory.CreateDirectory (_path);
- return true;
- } catch {
- return false;
- }
- }
-
- public bool RenameTo (FilePath file)
- {
- return RenameTo (file._path);
- }
-
- public bool RenameTo (string name)
- {
- return false; // FileHelper.Instance.RenameTo(this, name);
- }
-
- public bool SetLastModified (long milis)
- {
- return false; // FileHelper.Instance.SetLastModified(this, milis);
- }
-
- public bool SetReadOnly ()
- {
- return false; // FileHelper.Instance.SetReadOnly(this);
- }
-
- public Uri ToUri ()
- {
- return new Uri (_path);
- }
-
- // Don't change the case of this method, since ngit does reflection on it
- public bool CanExecute ()
- {
- return false; // FileHelper.Instance.CanExecute(this);
- }
-
- // Don't change the case of this method, since ngit does reflection on it
- public bool SetExecutable (bool exec)
- {
- return false; // FileHelper.Instance.SetExecutable(this, exec);
- }
-
- public string GetParent ()
- {
- string p = Path.GetDirectoryName (_path);
- if (string.IsNullOrEmpty(p) || p == _path)
- return null;
- return p;
- }
-
- public override string ToString ()
- {
- return _path;
- }
-
- static internal string PathSeparator {
- get { return Path.PathSeparator.ToString (); }
- }
-
- static internal char PathSeparatorChar {
- get { return Path.PathSeparator; }
- }
-
- static internal char SeparatorChar {
- get { return Path.DirectorySeparatorChar; }
- }
-
- static internal string Separator {
- get { return Path.DirectorySeparatorChar.ToString (); }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs
deleted file mode 100644
index 7a0c1f90e..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public class FileReader : InputStreamReader
- {
- //public FileReader (FilePath f) : base(f.GetPath ())
- //{
- //}
- //path -> fileStream
- public FileReader(InputStream s) : base(s)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs
deleted file mode 100644
index 0675c238b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- //resharper said, nobody using this. i believe it.
- //internal class FileWriter : StreamWriter
- //{
- // public FileWriter (FilePath path) : base(path.GetPath ())
- // {
- // }
-
- // public FileWriter Append (string sequence)
- // {
- // Write (sequence);
- // return this;
- // }
- //}
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs
deleted file mode 100644
index dfc0ba264..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public class FilterInputStream : InputStream
- {
- protected InputStream In;
-
- public FilterInputStream (InputStream s)
- {
- In = s;
- }
-
- public override int Available ()
- {
- return In.Available ();
- }
-
- public override void Close ()
- {
- In.Close ();
- }
-
- public override void Mark (int readlimit)
- {
- In.Mark (readlimit);
- }
-
- public override bool MarkSupported ()
- {
- return In.MarkSupported ();
- }
-
- public override int Read ()
- {
- return In.Read ();
- }
-
- public override int Read (byte[] buf)
- {
- return In.Read (buf);
- }
-
- public override int Read (byte[] b, int off, int len)
- {
- return In.Read (b, off, len);
- }
-
- public override void Reset ()
- {
- In.Reset ();
- }
-
- public override long Skip (long cnt)
- {
- return In.Skip (cnt);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs
deleted file mode 100644
index 4863105ed..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public class FilterOutputStream : OutputStream
- {
- protected OutputStream Out;
-
- public FilterOutputStream (OutputStream os)
- {
- Out = os;
- }
-
- public override void Close ()
- {
- Out.Close ();
- }
-
- public override void Flush ()
- {
- Out.Flush ();
- }
-
- public override void Write (byte[] b)
- {
- Out.Write (b);
- }
-
- public override void Write (int b)
- {
- Out.Write (b);
- }
-
- public override void Write (byte[] b, int offset, int len)
- {
- Out.Write (b, offset, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs
deleted file mode 100644
index c2c53485d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class Hashtable : Dictionary<object, object>
- {
- public void Put(object key, object value)
- {
- Add(key, value);
- }
-
- public object Get(object key)
- {
- var m_key = Keys.SingleOrDefault(k => k.Equals(key));
-
- return m_key != null ? this[m_key] : null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs
deleted file mode 100644
index ace314eee..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-//
-// HttpURLConnection.cs
-//
-// Author:
-// Lluis Sanchez Gual <lluis@novell.com>
-//
-// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class UrlConnection
- {
- protected Uri Url;
- }
-
-}
-
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs
deleted file mode 100644
index d847cb497..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal interface ICallable<T>
- {
- T Call ();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs
deleted file mode 100644
index dead24244..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal interface IConcurrentMap<T, TU> : IDictionary<T, TU>
- {
- TU PutIfAbsent (T key, TU value);
- bool Remove (object key, object value);
- bool Replace (T key, TU oldValue, TU newValue);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs
deleted file mode 100644
index 5f76c2ed5..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public interface IExecutor
- {
- void Execute (IRunnable runnable);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs
deleted file mode 100644
index fe2eb6a3d..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public interface IFilenameFilter
- {
- bool Accept (FilePath dir, string name);
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs
deleted file mode 100644
index 5215e4502..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal interface IFuture<T>
- {
- bool Cancel (bool mayInterruptIfRunning);
- T Get ();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs
deleted file mode 100644
index 4a5e92f9b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal interface IPrivilegedAction<T>
- {
- T Run ();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs
deleted file mode 100644
index 7f6ae5533..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public interface IRunnable
- {
- void Run ();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs
deleted file mode 100644
index 2f3f070b5..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs
+++ /dev/null
@@ -1,169 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class InputStream : IDisposable
- {
- private long _mark;
- protected Stream Wrapped;
- protected Stream BaseStream;
-
- public static implicit operator InputStream (Stream s)
- {
- return Wrap (s);
- }
-
- public static implicit operator Stream (InputStream s)
- {
- return s.GetWrappedStream ();
- }
-
- public virtual int Available ()
- {
- if (Wrapped is WrappedSystemStream)
- return ((WrappedSystemStream)Wrapped).InputStream.Available ();
- return 0;
- }
-
- public virtual void Close ()
- {
- if (Wrapped != null) {
- //Stream.`Close` method deleted
- //Wrapped.Close ();
- Wrapped.Dispose();
- }
- }
-
- public void Dispose ()
- {
- Close ();
- }
-
- internal Stream GetWrappedStream ()
- {
- // Always create a wrapper stream (not directly Wrapped) since the subclass
- // may be overriding methods that need to be called when used through the Stream class
- return new WrappedSystemStream (this);
- }
-
- public virtual void Mark (int readlimit)
- {
- if (Wrapped is WrappedSystemStream)
- ((WrappedSystemStream)Wrapped).InputStream.Mark (readlimit);
- else {
- if (BaseStream is WrappedSystemStream)
- ((WrappedSystemStream)BaseStream).OnMark (readlimit);
- if (Wrapped != null)
- _mark = Wrapped.Position;
- }
- }
-
- public virtual bool MarkSupported ()
- {
- if (Wrapped is WrappedSystemStream)
- return ((WrappedSystemStream)Wrapped).InputStream.MarkSupported ();
- return ((Wrapped != null) && Wrapped.CanSeek);
- }
-
- public virtual int Read ()
- {
- if (Wrapped == null) {
- throw new NotImplementedException ();
- }
- return Wrapped.ReadByte ();
- }
-
- public virtual int Read (byte[] buf)
- {
- return Read (buf, 0, buf.Length);
- }
-
- public virtual int Read (byte[] b, int off, int len)
- {
- if (Wrapped is WrappedSystemStream)
- return ((WrappedSystemStream)Wrapped).InputStream.Read (b, off, len);
-
- if (Wrapped != null) {
- int num = Wrapped.Read (b, off, len);
- return ((num <= 0) ? -1 : num);
- }
- int totalRead = 0;
- while (totalRead < len) {
- int nr = Read ();
- if (nr == -1)
- return -1;
- b[off + totalRead] = (byte)nr;
- totalRead++;
- }
- return totalRead;
- }
-
- public virtual void Reset ()
- {
- if (Wrapped is WrappedSystemStream)
- ((WrappedSystemStream)Wrapped).InputStream.Reset ();
- else {
- if (Wrapped == null)
- throw new IOException ();
- Wrapped.Position = _mark;
- }
- }
-
- public virtual long Skip (long cnt)
- {
- if (Wrapped is WrappedSystemStream)
- return ((WrappedSystemStream)Wrapped).InputStream.Skip (cnt);
-
- long n = cnt;
- while (n > 0) {
- if (Read () == -1)
- return cnt - n;
- n--;
- }
- return cnt - n;
- }
-
- internal virtual bool CanSeek ()
- {
- if (Wrapped != null)
- return Wrapped.CanSeek;
- return false;
- }
-
- internal virtual long Position {
- get
- {
- if (Wrapped != null)
- return Wrapped.Position;
- throw new NotSupportedException ();
- }
- set {
- if (Wrapped != null)
- Wrapped.Position = value;
- else
- throw new NotSupportedException ();
- }
- }
-
- public virtual long Length
- {
- get
- {
- if (Wrapped != null)
- {
- return Wrapped.Length;
- }
-
- throw new NotSupportedException();
- }
- }
-
- static internal InputStream Wrap (Stream s)
- {
- InputStream stream = new InputStream ();
- stream.Wrapped = s;
- return stream;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs
deleted file mode 100644
index f9f1983b8..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.IO;
-using System.Text;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class InputStreamReader : StreamReader
- {
- //Stream(string path) constructor deleted
- //protected InputStreamReader (string file) : base(file)
- //{
- //}
-
- public InputStreamReader (InputStream s) : base(s.GetWrappedStream ())
- {
- }
-
- public InputStreamReader (InputStream s, string encoding) : base(s.GetWrappedStream (), Encoding.GetEncoding (encoding))
- {
- }
-
- public InputStreamReader (InputStream s, Encoding e) : base(s.GetWrappedStream (), e)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs
deleted file mode 100644
index 634c7b404..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- public interface ITerator
- {
- bool HasNext ();
- object Next ();
- void Remove ();
- }
-
- public abstract class Iterator<T> : IEnumerator<T>, ITerator
- {
- private T _lastValue;
-
- object ITerator.Next ()
- {
- return Next ();
- }
-
- public abstract bool HasNext ();
- public abstract T Next ();
- public abstract void Remove ();
-
- bool IEnumerator.MoveNext ()
- {
- if (HasNext ()) {
- _lastValue = Next ();
- return true;
- }
- return false;
- }
-
- void IEnumerator.Reset ()
- {
- throw new NotImplementedException ();
- }
-
- void IDisposable.Dispose ()
- {
- }
-
- T IEnumerator<T>.Current {
- get { return _lastValue; }
- }
-
- object IEnumerator.Current {
- get { return _lastValue; }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs
deleted file mode 100644
index 9f4970bdd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class LinkageError : Exception
- {
- public LinkageError (string msg) : base(msg)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs
deleted file mode 100644
index 50f3fa43b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs
+++ /dev/null
@@ -1,275 +0,0 @@
-//Copyright (c) Microsoft Corporation. All rights reserved.
-
-using System;
-using System.Text;
-
-namespace SharpCifs.Util.Sharpen
-{ // **************************************************************
-// * Raw implementation of the MD5 hash algorithm
-// * from RFC 1321.
-// *
-// * Written By: Reid Borsuk and Jenny Zheng
-// * Copyright (c) Microsoft Corporation. All rights reserved.
-// **************************************************************
-
-// Simple struct for the (a,b,c,d) which is used to compute the mesage digest.
- struct AbcdStruct
- {
- public uint A;
- public uint B;
- public uint C;
- public uint D;
- }
-
- public sealed class Md5Core
- {
- //Prevent CSC from adding a default public constructor
- private Md5Core() { }
-
- public static byte[] GetHash(string input, Encoding encoding)
- {
- if (null == input)
- throw new ArgumentNullException("input", "Unable to calculate hash over null input data");
- if (null == encoding)
- throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding");
-
- byte[] target = encoding.GetBytes(input);
-
- return GetHash(target);
- }
-
- public static byte[] GetHash(string input)
- {
- return GetHash(input, new UTF8Encoding());
- }
-
- public static string GetHashString(byte[] input)
- {
- if (null == input)
- throw new ArgumentNullException("input", "Unable to calculate hash over null input data");
-
- string retval = BitConverter.ToString(GetHash(input));
- retval = retval.Replace("-", "");
-
- return retval;
- }
-
- public static string GetHashString(string input, Encoding encoding)
- {
- if (null == input)
- throw new ArgumentNullException("input", "Unable to calculate hash over null input data");
- if (null == encoding)
- throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHashString(string) overload to use UTF8 Encoding");
-
- byte[] target = encoding.GetBytes(input);
-
- return GetHashString(target);
- }
-
- public static string GetHashString(string input)
- {
- return GetHashString(input, new UTF8Encoding());
- }
-
- public static byte[] GetHash(byte[] input)
- {
- if (null == input)
- throw new ArgumentNullException("input", "Unable to calculate hash over null input data");
-
- //Intitial values defined in RFC 1321
- AbcdStruct abcd = new AbcdStruct();
- abcd.A = 0x67452301;
- abcd.B = 0xefcdab89;
- abcd.C = 0x98badcfe;
- abcd.D = 0x10325476;
-
- //We pass in the input array by block, the final block of data must be handled specialy for padding & length embeding
- int startIndex = 0;
- while (startIndex <= input.Length - 64)
- {
- GetHashBlock(input, ref abcd, startIndex);
- startIndex += 64;
- }
- // The final data block.
- return GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64)input.Length * 8);
- }
-
- internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, AbcdStruct abcd, Int64 len)
- {
- byte[] working = new byte[64];
- byte[] length = BitConverter.GetBytes(len);
-
- //Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321
- //The CLR ensures that our buffer is 0-assigned, we don't need to explicitly set it. This is why it ends up being quicker to just
- //use a temporary array rather then doing in-place assignment (5% for small inputs)
- Array.Copy(input, ibStart, working, 0, cbSize);
- working[cbSize] = 0x80;
-
- //We have enough room to store the length in this chunk
- if (cbSize < 56)
- {
- Array.Copy(length, 0, working, 56, 8);
- GetHashBlock(working, ref abcd, 0);
- }
- else //We need an aditional chunk to store the length
- {
- GetHashBlock(working, ref abcd, 0);
- //Create an entirely new chunk due to the 0-assigned trick mentioned above, to avoid an extra function call clearing the array
- working = new byte[64];
- Array.Copy(length, 0, working, 56, 8);
- GetHashBlock(working, ref abcd, 0);
- }
- byte[] output = new byte[16];
- Array.Copy(BitConverter.GetBytes(abcd.A), 0, output, 0, 4);
- Array.Copy(BitConverter.GetBytes(abcd.B), 0, output, 4, 4);
- Array.Copy(BitConverter.GetBytes(abcd.C), 0, output, 8, 4);
- Array.Copy(BitConverter.GetBytes(abcd.D), 0, output, 12, 4);
- return output;
- }
-
- // Performs a single block transform of MD5 for a given set of ABCD inputs
- /* If implementing your own hashing framework, be sure to set the initial ABCD correctly according to RFC 1321:
- // A = 0x67452301;
- // B = 0xefcdab89;
- // C = 0x98badcfe;
- // D = 0x10325476;
- */
- internal static void GetHashBlock(byte[] input, ref AbcdStruct abcdValue, int ibStart)
- {
- uint[] temp = Converter(input, ibStart);
- uint a = abcdValue.A;
- uint b = abcdValue.B;
- uint c = abcdValue.C;
- uint d = abcdValue.D;
-
- a = R1(a, b, c, d, temp[0], 7, 0xd76aa478);
- d = R1(d, a, b, c, temp[1], 12, 0xe8c7b756);
- c = R1(c, d, a, b, temp[2], 17, 0x242070db);
- b = R1(b, c, d, a, temp[3], 22, 0xc1bdceee);
- a = R1(a, b, c, d, temp[4], 7, 0xf57c0faf);
- d = R1(d, a, b, c, temp[5], 12, 0x4787c62a);
- c = R1(c, d, a, b, temp[6], 17, 0xa8304613);
- b = R1(b, c, d, a, temp[7], 22, 0xfd469501);
- a = R1(a, b, c, d, temp[8], 7, 0x698098d8);
- d = R1(d, a, b, c, temp[9], 12, 0x8b44f7af);
- c = R1(c, d, a, b, temp[10], 17, 0xffff5bb1);
- b = R1(b, c, d, a, temp[11], 22, 0x895cd7be);
- a = R1(a, b, c, d, temp[12], 7, 0x6b901122);
- d = R1(d, a, b, c, temp[13], 12, 0xfd987193);
- c = R1(c, d, a, b, temp[14], 17, 0xa679438e);
- b = R1(b, c, d, a, temp[15], 22, 0x49b40821);
-
- a = R2(a, b, c, d, temp[1], 5, 0xf61e2562);
- d = R2(d, a, b, c, temp[6], 9, 0xc040b340);
- c = R2(c, d, a, b, temp[11], 14, 0x265e5a51);
- b = R2(b, c, d, a, temp[0], 20, 0xe9b6c7aa);
- a = R2(a, b, c, d, temp[5], 5, 0xd62f105d);
- d = R2(d, a, b, c, temp[10], 9, 0x02441453);
- c = R2(c, d, a, b, temp[15], 14, 0xd8a1e681);
- b = R2(b, c, d, a, temp[4], 20, 0xe7d3fbc8);
- a = R2(a, b, c, d, temp[9], 5, 0x21e1cde6);
- d = R2(d, a, b, c, temp[14], 9, 0xc33707d6);
- c = R2(c, d, a, b, temp[3], 14, 0xf4d50d87);
- b = R2(b, c, d, a, temp[8], 20, 0x455a14ed);
- a = R2(a, b, c, d, temp[13], 5, 0xa9e3e905);
- d = R2(d, a, b, c, temp[2], 9, 0xfcefa3f8);
- c = R2(c, d, a, b, temp[7], 14, 0x676f02d9);
- b = R2(b, c, d, a, temp[12], 20, 0x8d2a4c8a);
-
- a = R3(a, b, c, d, temp[5], 4, 0xfffa3942);
- d = R3(d, a, b, c, temp[8], 11, 0x8771f681);
- c = R3(c, d, a, b, temp[11], 16, 0x6d9d6122);
- b = R3(b, c, d, a, temp[14], 23, 0xfde5380c);
- a = R3(a, b, c, d, temp[1], 4, 0xa4beea44);
- d = R3(d, a, b, c, temp[4], 11, 0x4bdecfa9);
- c = R3(c, d, a, b, temp[7], 16, 0xf6bb4b60);
- b = R3(b, c, d, a, temp[10], 23, 0xbebfbc70);
- a = R3(a, b, c, d, temp[13], 4, 0x289b7ec6);
- d = R3(d, a, b, c, temp[0], 11, 0xeaa127fa);
- c = R3(c, d, a, b, temp[3], 16, 0xd4ef3085);
- b = R3(b, c, d, a, temp[6], 23, 0x04881d05);
- a = R3(a, b, c, d, temp[9], 4, 0xd9d4d039);
- d = R3(d, a, b, c, temp[12], 11, 0xe6db99e5);
- c = R3(c, d, a, b, temp[15], 16, 0x1fa27cf8);
- b = R3(b, c, d, a, temp[2], 23, 0xc4ac5665);
-
- a = R4(a, b, c, d, temp[0], 6, 0xf4292244);
- d = R4(d, a, b, c, temp[7], 10, 0x432aff97);
- c = R4(c, d, a, b, temp[14], 15, 0xab9423a7);
- b = R4(b, c, d, a, temp[5], 21, 0xfc93a039);
- a = R4(a, b, c, d, temp[12], 6, 0x655b59c3);
- d = R4(d, a, b, c, temp[3], 10, 0x8f0ccc92);
- c = R4(c, d, a, b, temp[10], 15, 0xffeff47d);
- b = R4(b, c, d, a, temp[1], 21, 0x85845dd1);
- a = R4(a, b, c, d, temp[8], 6, 0x6fa87e4f);
- d = R4(d, a, b, c, temp[15], 10, 0xfe2ce6e0);
- c = R4(c, d, a, b, temp[6], 15, 0xa3014314);
- b = R4(b, c, d, a, temp[13], 21, 0x4e0811a1);
- a = R4(a, b, c, d, temp[4], 6, 0xf7537e82);
- d = R4(d, a, b, c, temp[11], 10, 0xbd3af235);
- c = R4(c, d, a, b, temp[2], 15, 0x2ad7d2bb);
- b = R4(b, c, d, a, temp[9], 21, 0xeb86d391);
-
- abcdValue.A = unchecked(a + abcdValue.A);
- abcdValue.B = unchecked(b + abcdValue.B);
- abcdValue.C = unchecked(c + abcdValue.C);
- abcdValue.D = unchecked(d + abcdValue.D);
- }
-
- //Manually unrolling these equations nets us a 20% performance improvement
- private static uint R1(uint a, uint b, uint c, uint d, uint x, int s, uint t)
- {
- // (b + LSR((a + F(b, c, d) + x + t), s))
- //F(x, y, z) ((x & y) | ((x ^ 0xFFFFFFFF) & z))
- return unchecked(b + Lsr((a + ((b & c) | ((b ^ 0xFFFFFFFF) & d)) + x + t), s));
- }
-
- private static uint R2(uint a, uint b, uint c, uint d, uint x, int s, uint t)
- {
- // (b + LSR((a + G(b, c, d) + x + t), s))
- //G(x, y, z) ((x & z) | (y & (z ^ 0xFFFFFFFF)))
- return unchecked(b + Lsr((a + ((b & d) | (c & (d ^ 0xFFFFFFFF))) + x + t), s));
- }
-
- private static uint R3(uint a, uint b, uint c, uint d, uint x, int s, uint t)
- {
- // (b + LSR((a + H(b, c, d) + k + i), s))
- //H(x, y, z) (x ^ y ^ z)
- return unchecked(b + Lsr((a + (b ^ c ^ d) + x + t), s));
- }
-
- private static uint R4(uint a, uint b, uint c, uint d, uint x, int s, uint t)
- {
- // (b + LSR((a + I(b, c, d) + k + i), s))
- //I(x, y, z) (y ^ (x | (z ^ 0xFFFFFFFF)))
- return unchecked(b + Lsr((a + (c ^ (b | (d ^ 0xFFFFFFFF))) + x + t), s));
- }
-
- // Implementation of left rotate
- // s is an int instead of a uint becuase the CLR requires the argument passed to >>/<< is of
- // type int. Doing the demoting inside this function would add overhead.
- private static uint Lsr(uint i, int s)
- {
- return ((i << s) | (i >> (32 - s)));
- }
-
- //Convert input array into array of UInts
- private static uint[] Converter(byte[] input, int ibStart)
- {
- if (null == input)
- throw new ArgumentNullException("input", "Unable convert null array to array of uInts");
-
- uint[] result = new uint[16];
-
- for (int i = 0; i < 16; i++)
- {
- result[i] = input[ibStart + i * 4];
- result[i] += (uint)input[ibStart + i * 4 + 1] << 8;
- result[i] += (uint)input[ibStart + i * 4 + 2] << 16;
- result[i] += (uint)input[ibStart + i * 4 + 3] << 24;
- }
-
- return result;
- }
- }
-} \ No newline at end of file
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs
deleted file mode 100644
index e74a05abf..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-//Copyright (c) Microsoft Corporation. All rights reserved.
-
-using System;
-using System.Security.Cryptography;
-
-// **************************************************************
-// * Raw implementation of the MD5 hash algorithm
-// * from RFC 1321.
-// *
-// * Written By: Reid Borsuk and Jenny Zheng
-// * Copyright (c) Microsoft Corporation. All rights reserved.
-// **************************************************************
-
-
-#if SILVERLIGHT
-#else
-//public class MD5Managed : MD5
-#endif
-namespace SharpCifs.Util.Sharpen
-{
- public class Md5Managed : HashAlgorithm
-
- {
- public static Md5Managed Create()
- {
- return new Md5Managed();
- }
-
- private byte[] _data;
- private AbcdStruct _abcd;
- private Int64 _totalLength;
- private int _dataSize;
-
- public Md5Managed()
- {
- //field cannot access
- //HashSizeValue = 0x80;
- Initialize();
- }
-
- public override void Initialize()
- {
- _data = new byte[64];
- _dataSize = 0;
- _totalLength = 0;
- _abcd = new AbcdStruct();
- //Intitial values as defined in RFC 1321
- _abcd.A = 0x67452301;
- _abcd.B = 0xefcdab89;
- _abcd.C = 0x98badcfe;
- _abcd.D = 0x10325476;
- }
-
- protected override void HashCore(byte[] array, int ibStart, int cbSize)
- {
- int startIndex = ibStart;
- int totalArrayLength = _dataSize + cbSize;
- if (totalArrayLength >= 64)
- {
- Array.Copy(array, startIndex, _data, _dataSize, 64 - _dataSize);
- // Process message of 64 bytes (512 bits)
- Md5Core.GetHashBlock(_data, ref _abcd, 0);
- startIndex += 64 - _dataSize;
- totalArrayLength -= 64;
- while (totalArrayLength >= 64)
- {
- Array.Copy(array, startIndex, _data, 0, 64);
- Md5Core.GetHashBlock(array, ref _abcd, startIndex);
- totalArrayLength -= 64;
- startIndex += 64;
- }
- _dataSize = totalArrayLength;
- Array.Copy(array, startIndex, _data, 0, totalArrayLength);
- }
- else
- {
- Array.Copy(array, startIndex, _data, _dataSize, cbSize);
- _dataSize = totalArrayLength;
- }
- _totalLength += cbSize;
- }
-
- protected override byte[] HashFinal()
- {
- //field cannot access
- //HashValue = Md5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8);
- //return HashValue;
- return Md5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs
deleted file mode 100644
index d0bd79aa2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System;
-using System.Text.RegularExpressions;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class Matcher
- {
- private int _current;
- private MatchCollection _matches;
- private Regex _regex;
- private string _str;
-
- internal Matcher (Regex regex, string str)
- {
- this._regex = regex;
- this._str = str;
- }
-
- public int End ()
- {
- if ((_matches == null) || (_current >= _matches.Count)) {
- throw new InvalidOperationException ();
- }
- return (_matches[_current].Index + _matches[_current].Length);
- }
-
- public bool Find ()
- {
- if (_matches == null) {
- _matches = _regex.Matches (_str);
- _current = 0;
- }
- return (_current < _matches.Count);
- }
-
- public bool Find (int index)
- {
- _matches = _regex.Matches (_str, index);
- _current = 0;
- return (_matches.Count > 0);
- }
-
- public string Group (int n)
- {
- if ((_matches == null) || (_current >= _matches.Count)) {
- throw new InvalidOperationException ();
- }
- Group grp = _matches[_current].Groups[n];
- return grp.Success ? grp.Value : null;
- }
-
- public bool Matches ()
- {
- _matches = null;
- return Find ();
- }
-
- public string ReplaceFirst (string txt)
- {
- return _regex.Replace (_str, txt, 1);
- }
-
- public Matcher Reset (CharSequence str)
- {
- return Reset (str.ToString ());
- }
-
- public Matcher Reset (string str)
- {
- _matches = null;
- this._str = str;
- return this;
- }
-
- public int Start ()
- {
- if ((_matches == null) || (_current >= _matches.Count)) {
- throw new InvalidOperationException ();
- }
- return _matches[_current].Index;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs
deleted file mode 100644
index 5562f9d36..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-using System.Security.Cryptography;
-
-namespace SharpCifs.Util.Sharpen
-{
- public abstract class MessageDigest
- {
- public void Digest (byte[] buffer, int o, int len)
- {
- byte[] d = Digest ();
- d.CopyTo (buffer, o);
- }
-
- public byte[] Digest (byte[] buffer)
- {
- Update (buffer);
- return Digest ();
- }
-
- public abstract byte[] Digest ();
- public abstract int GetDigestLength ();
- public static MessageDigest GetInstance (string algorithm)
- {
- switch (algorithm.ToLower ()) {
- case "sha-1":
- //System.Security.CryptographySHA1Managed not found
- //return new MessageDigest<SHA1Managed> ();
- return new MessageDigest<System.Security.Cryptography.SHA1>();
- case "md5":
- return new MessageDigest<Md5Managed> ();
- }
- throw new NotSupportedException (string.Format ("The requested algorithm \"{0}\" is not supported.", algorithm));
- }
-
- public abstract void Reset ();
- public abstract void Update (byte[] b);
- public abstract void Update (byte b);
- public abstract void Update (byte[] b, int offset, int len);
- }
-
-
- public class MessageDigest<TAlgorithm> : MessageDigest where TAlgorithm : HashAlgorithm //, new() //use static `Create` method
- {
- private TAlgorithm _hash;
- //private CryptoStream _stream; //don't work .NET Core
- private MemoryStream _stream;
-
-
- public MessageDigest ()
- {
- Init ();
- }
-
- public override byte[] Digest ()
- {
- //CryptoStream -> MemoryStream, needless method
- //_stream.FlushFinalBlock ();
-
- //HashAlgorithm.`Hash` property deleted
- //byte[] hash = _hash.Hash;
- byte[] hash = _hash.ComputeHash(_stream.ToArray());
-
- Reset ();
- return hash;
- }
-
- public void Dispose ()
- {
- if (_stream != null) {
- _stream.Dispose ();
- }
- _stream = null;
- }
-
- public override int GetDigestLength ()
- {
- return (_hash.HashSize / 8);
- }
-
- private void Init ()
- {
- //use static `Create` method
- //_hash = Activator.CreateInstance<TAlgorithm> ();
- var createMethod = typeof(TAlgorithm).GetRuntimeMethod("Create", new Type[0]);
- _hash = (TAlgorithm)createMethod.Invoke(null, new object[] {});
-
- //HashAlgorithm cannot cast `ICryptoTransform` on .NET Core, gave up using CryptoStream.
- //_stream = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write);
- //_stream = new CryptoStream(_tmpStream, (ICryptoTransform)_hash, CryptoStreamMode.Write);
- _stream = new MemoryStream();
- }
-
- public override void Reset ()
- {
- Dispose ();
- Init ();
- }
-
- public override void Update (byte[] input)
- {
- _stream.Write (input, 0, input.Length);
- }
-
- public override void Update (byte input)
- {
- _stream.WriteByte (input);
- }
-
- public override void Update (byte[] input, int index, int count)
- {
- if (count < 0)
- Console.WriteLine ("Argh!");
- _stream.Write (input, index, count);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs
deleted file mode 100644
index 05599cea3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class NetworkStream : Stream
- {
- SocketEx _socket;
-
- public NetworkStream(SocketEx socket)
- {
- _socket = socket;
- }
-
- public override bool CanRead
- {
- get { throw new NotImplementedException(); }
- }
-
- public override bool CanSeek
- {
- get { throw new NotImplementedException(); }
- }
-
- public override bool CanWrite
- {
- get { throw new NotImplementedException(); }
- }
-
- public override void Flush()
- {
- // throw new NotImplementedException();
- }
-
- public override long Length
- {
- get { throw new NotImplementedException(); }
- }
-
- public override long Position
- {
- get
- {
- throw new NotImplementedException();
- }
- set
- {
- throw new NotImplementedException();
- }
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- return _socket.Receive(buffer, offset, count);
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotImplementedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotImplementedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- _socket.Send(buffer, offset, count);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs
deleted file mode 100644
index dc3d6ccc3..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class ObjectInputStream : InputStream
- {
- private BinaryReader _reader;
-
- public ObjectInputStream (InputStream s)
- {
- _reader = new BinaryReader (s.GetWrappedStream ());
- }
-
- public int ReadInt ()
- {
- return _reader.ReadInt32 ();
- }
-
- public object ReadObject ()
- {
- throw new NotImplementedException ();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs
deleted file mode 100644
index 97f3a2cfd..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class ObjectOutputStream : OutputStream
- {
- private BinaryWriter _bw;
-
- public ObjectOutputStream (OutputStream os)
- {
- _bw = new BinaryWriter (os.GetWrappedStream ());
- }
-
- public virtual void WriteInt (int i)
- {
- _bw.Write (i);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs
deleted file mode 100644
index 0e6189f0c..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class OutputStream : IDisposable
- {
- protected Stream Wrapped;
-
- public static implicit operator OutputStream (Stream s)
- {
- return Wrap (s);
- }
-
- public static implicit operator Stream (OutputStream s)
- {
- return s.GetWrappedStream ();
- }
-
- public virtual void Close ()
- {
- if (Wrapped != null) {
- //Stream.`Close` method deleted
- //Wrapped.Close ();
- Wrapped.Dispose();
- }
- }
-
- public void Dispose ()
- {
- Close ();
- }
-
- public virtual void Flush ()
- {
- if (Wrapped != null) {
- Wrapped.Flush ();
- }
- }
-
- internal Stream GetWrappedStream ()
- {
- // Always create a wrapper stream (not directly Wrapped) since the subclass
- // may be overriding methods that need to be called when used through the Stream class
- return new WrappedSystemStream (this);
- }
-
- static internal OutputStream Wrap (Stream s)
- {
- OutputStream stream = new OutputStream ();
- stream.Wrapped = s;
- return stream;
- }
-
- public virtual void Write (int b)
- {
- if (Wrapped is WrappedSystemStream)
- ((WrappedSystemStream)Wrapped).OutputStream.Write (b);
- else {
- if (Wrapped == null)
- throw new NotImplementedException ();
- Wrapped.WriteByte ((byte)b);
- }
- }
-
- public virtual void Write (byte[] b)
- {
- Write (b, 0, b.Length);
- }
-
- public virtual void Write (byte[] b, int offset, int len)
- {
- if (Wrapped is WrappedSystemStream)
- ((WrappedSystemStream)Wrapped).OutputStream.Write (b, offset, len);
- else {
- if (Wrapped != null) {
- Wrapped.Write (b, offset, len);
- } else {
- for (int i = 0; i < len; i++) {
- Write (b[i + offset]);
- }
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs
deleted file mode 100644
index 6313b7c79..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.IO;
-using System.Text;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class OutputStreamWriter : StreamWriter
- {
- public OutputStreamWriter (OutputStream stream) : base(stream.GetWrappedStream ())
- {
- }
-
- public OutputStreamWriter (OutputStream stream, string encoding) : base(stream.GetWrappedStream (), Extensions.GetEncoding (encoding))
- {
- }
-
- public OutputStreamWriter (OutputStream stream, Encoding encoding) : base(stream.GetWrappedStream (), encoding)
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs
deleted file mode 100644
index d5004c988..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-using System;
-using System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class PipedInputStream : InputStream
- {
- private byte[] _oneBuffer;
- public const int PipeSize = 1024;
-
- protected byte[] Buffer;
- private bool _closed;
- private ManualResetEvent _dataEvent;
- private int _end;
- private int _start;
- private object _thisLock;
- private bool _allowGrow = false;
-
- public int In {
- get { return _start; }
- set { _start = value; }
- }
-
- public int Out {
- get { return _end; }
- set { _end = value; }
- }
-
- public PipedInputStream ()
- {
- _thisLock = new object ();
- _dataEvent = new ManualResetEvent (false);
- Buffer = new byte[PipeSize + 1];
- }
-
- public PipedInputStream (PipedOutputStream os): this ()
- {
- os.Attach (this);
- }
-
- public override void Close ()
- {
- lock (_thisLock) {
- _closed = true;
- _dataEvent.Set ();
- }
- }
-
- public override int Available ()
- {
- lock (_thisLock) {
- if (_start <= _end) {
- return (_end - _start);
- }
- return ((Buffer.Length - _start) + _end);
- }
- }
-
- public override int Read ()
- {
- if (_oneBuffer == null)
- _oneBuffer = new byte[1];
- if (Read (_oneBuffer, 0, 1) == -1)
- return -1;
- return _oneBuffer[0];
- }
-
- public override int Read (byte[] b, int offset, int len)
- {
- int length = 0;
- do {
- _dataEvent.WaitOne ();
- lock (_thisLock) {
- if (_closed && Available () == 0) {
- return -1;
- }
- if (_start < _end) {
- length = Math.Min (len, _end - _start);
- Array.Copy (Buffer, _start, b, offset, length);
- _start += length;
- } else if (_start > _end) {
- length = Math.Min (len, Buffer.Length - _start);
- Array.Copy (Buffer, _start, b, offset, length);
- len -= length;
- _start = (_start + length) % Buffer.Length;
- if (len > 0) {
- int i = Math.Min (len, _end);
- Array.Copy (Buffer, 0, b, offset + length, i);
- _start += i;
- length += i;
- }
- }
- if (_start == _end && !_closed) {
- _dataEvent.Reset ();
- }
- Monitor.PulseAll (_thisLock);
- }
- } while (length == 0);
- return length;
- }
-
- private int Allocate (int len)
- {
- int alen;
- while ((alen = TryAllocate (len)) == 0) {
- // Wait until somebody reads data
- try {
- Monitor.Wait (_thisLock);
- } catch {
- _closed = true;
- _dataEvent.Set ();
- throw;
- }
- }
- return alen;
- }
-
- int TryAllocate (int len)
- {
- int free;
- if (_start <= _end) {
- free = (Buffer.Length - _end) + _start;
- } else {
- free = _start - _end;
- }
- if (free <= len) {
- if (!_allowGrow)
- return free > 0 ? free - 1 : 0;
- int sizeInc = (len - free) + 1;
- byte[] destinationArray = new byte[Buffer.Length + sizeInc];
- if (_start <= _end) {
- Array.Copy (Buffer, _start, destinationArray, _start, _end - _start);
- } else {
- Array.Copy (Buffer, 0, destinationArray, 0, _end);
- Array.Copy (Buffer, _start, destinationArray, _start + sizeInc, Buffer.Length - _start);
- _start += sizeInc;
- }
- Buffer = destinationArray;
- }
- return len;
- }
-
- internal void Write (int b)
- {
- lock (_thisLock) {
- Allocate (1);
- Buffer[_end] = (byte)b;
- _end = (_end + 1) % Buffer.Length;
- _dataEvent.Set ();
- }
- }
-
- internal void Write (byte[] b, int offset, int len)
- {
- do {
- lock (_thisLock) {
- int alen = Allocate (len);
- int length = Math.Min (Buffer.Length - _end, alen);
- Array.Copy (b, offset, Buffer, _end, length);
- _end = (_end + length) % Buffer.Length;
- if (length < alen) {
- Array.Copy (b, offset + length, Buffer, 0, alen - length);
- _end += alen - length;
- }
- _dataEvent.Set ();
- len -= alen;
- offset += alen;
- }
- } while (len > 0);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs
deleted file mode 100644
index 4c46f1ec0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal class PipedOutputStream : OutputStream
- {
- PipedInputStream _ips;
-
- public PipedOutputStream ()
- {
- }
-
- public PipedOutputStream (PipedInputStream iss) : this()
- {
- Attach (iss);
- }
-
- public override void Close ()
- {
- _ips.Close ();
- base.Close ();
- }
-
- internal void Attach (PipedInputStream iss)
- {
- _ips = iss;
- }
-
- public override void Write (int b)
- {
- _ips.Write (b);
- }
-
- public override void Write (byte[] b, int offset, int len)
- {
- _ips.Write (b, offset, len);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs
deleted file mode 100644
index c366aa665..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs
+++ /dev/null
@@ -1,231 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class PrintWriter : TextWriter
- {
- TextWriter _writer;
- private FileStream _stream;
-
- public PrintWriter (FilePath path)
- {
- //Stream(string path) constructor deleted
- _stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
- _writer = new StreamWriter (_stream);
- }
-
- public PrintWriter (TextWriter other)
- {
- _writer = other;
- }
-
- public override Encoding Encoding {
- get { return _writer.Encoding; }
- }
-
- public void Close() // remove `override`
- {
- //Stream.`Close` method deleted
- //_writer.Close ();
- _writer.Dispose();
- _stream.Dispose();
- }
-
- public override void Flush ()
- {
- _writer.Flush ();
- }
-
- public override IFormatProvider FormatProvider {
- get {
- return _writer.FormatProvider;
- }
- }
-
- public override string NewLine {
- get {
- return _writer.NewLine;
- }
- set {
- _writer.NewLine = value;
- }
- }
-
- public override void Write (char[] buffer, int index, int count)
- {
- _writer.Write (buffer, index, count);
- }
-
- public override void Write (char[] buffer)
- {
- _writer.Write (buffer);
- }
-
- public void Write (string format, object arg0, object arg1, object arg2)
- {
- _writer.Write (format, arg0, arg1, arg2);
- }
-
- public override void Write (string format, object arg0, object arg1)
- {
- _writer.Write (format, arg0, arg1);
- }
-
- public override void Write (string format, object arg0)
- {
- _writer.Write (format, arg0);
- }
-
- public override void Write (string format, params object[] arg)
- {
- _writer.Write (format, arg);
- }
-
- public override void WriteLine (char[] buffer, int index, int count)
- {
- _writer.WriteLine (buffer, index, count);
- }
-
- public override void WriteLine (char[] buffer)
- {
- _writer.WriteLine (buffer);
- }
-
- public void WriteLine (string format, object arg0, object arg1, object arg2)
- {
- _writer.WriteLine (format, arg0, arg1, arg2);
- }
-
- public override void WriteLine (string format, object arg0, object arg1)
- {
- _writer.WriteLine (format, arg0, arg1);
- }
-
- public override void WriteLine (string format, object arg0)
- {
- _writer.WriteLine (format, arg0);
- }
-
- public override void WriteLine (string format, params object[] arg)
- {
- _writer.WriteLine (format, arg);
- }
-
- public override void WriteLine (ulong value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (uint value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (string value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (float value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (object value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (long value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (int value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (double value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (decimal value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (char value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine (bool value)
- {
- _writer.WriteLine (value);
- }
-
- public override void WriteLine ()
- {
- _writer.WriteLine ();
- }
-
- public override void Write (bool value)
- {
- _writer.Write (value);
- }
-
- public override void Write (char value)
- {
- _writer.Write (value);
- }
-
- public override void Write (decimal value)
- {
- _writer.Write (value);
- }
-
- public override void Write (double value)
- {
- _writer.Write (value);
- }
-
- public override void Write (int value)
- {
- _writer.Write (value);
- }
-
- public override void Write (long value)
- {
- _writer.Write (value);
- }
-
- public override void Write (object value)
- {
- _writer.Write (value);
- }
-
- public override void Write (float value)
- {
- _writer.Write (value);
- }
-
- public override void Write (string value)
- {
- _writer.Write (value);
- }
-
- public override void Write (uint value)
- {
- _writer.Write (value);
- }
-
- public override void Write (ulong value)
- {
- _writer.Write (value);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs
deleted file mode 100644
index 3d886ea87..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class Properties
- {
- protected Hashtable _properties;
-
- public Properties()
- {
- _properties = new Hashtable();
- }
-
- public Properties(Properties defaultProp): this()
- {
- PutAll(defaultProp._properties);
- }
-
- public void PutAll(Hashtable properties)
- {
- foreach (var key in properties.Keys)
- {
- //_properties.Add(key, properties[key]);
- _properties.Put(key, properties[key]);
- }
- }
-
- public void SetProperty(object key, object value)
- {
- //_properties.Add(key, value);
- _properties.Put(key, value);
- }
-
- public object GetProperty(object key)
- {
- return _properties.Keys.Contains(key) ? _properties[key] : null;
- }
-
- public object GetProperty(object key, object def)
- {
- /*if (_properties.ContainsKey(key))
- {
- return _properties[key];
- }
- return def;*/
- object value = _properties.Get(key);
-
- return value ?? def;
- }
-
- public void Load(InputStream input)
- {
- StreamReader sr = new StreamReader(input);
- while (!sr.EndOfStream)
- {
- string line = sr.ReadLine();
-
- if (!string.IsNullOrEmpty(line))
- {
- string[] tokens = line.Split('=');
- //_properties.Add(tokens[0], tokens[1]);
- _properties.Put(tokens[0], tokens[1]);
- }
- }
- }
-
- public void Store(OutputStream output)
- {
- StreamWriter sw = new StreamWriter(output);
- foreach (var key in _properties.Keys)
- {
- string line = string.Format("{0}={1}", key, _properties[key]);
- sw.WriteLine(line);
- }
- }
-
- public void Store(TextWriter output)
- {
- foreach (var key in _properties.Keys)
- {
- string line = string.Format("{0}={1}", key, _properties[key]);
- output.WriteLine(line);
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs
deleted file mode 100644
index bf3596212..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class RandomAccessFile
- {
- private FileStream _stream;
-
- public RandomAccessFile (FilePath file, string mode) : this(file.GetPath (), mode)
- {
- }
-
- public RandomAccessFile (string file, string mode)
- {
- if (mode.IndexOf ('w') != -1)
- _stream = new FileStream (file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- else
- _stream = new FileStream (file, FileMode.Open, FileAccess.Read);
- }
-
- public void Close ()
- {
- //Stream.`Close` method deleted
- //_stream.Close ();
- _stream.Dispose();
- }
-
- public long GetFilePointer ()
- {
- return _stream.Position;
- }
-
- public long Length ()
- {
- return _stream.Length;
- }
-
- public int Read (byte[] buffer)
- {
- int r = _stream.Read (buffer, 0, buffer.Length);
- return r > 0 ? r : -1;
- }
-
- public int Read (byte[] buffer, int start, int size)
- {
- return _stream.Read (buffer, start, size);
- }
-
- public void ReadFully (byte[] buffer, int start, int size)
- {
- while (size > 0) {
- int num = _stream.Read (buffer, start, size);
- if (num == 0) {
- throw new EofException ();
- }
- size -= num;
- start += num;
- }
- }
-
- public void Seek (long pos)
- {
- _stream.Position = pos;
- }
-
- public void SetLength (long len)
- {
- _stream.SetLength (len);
- }
-
- public void Write (int value)
- {
- _stream.Write (BitConverter.GetBytes (value), 0, 4);
- }
-
- public void Write (byte[] buffer)
- {
- _stream.Write (buffer, 0, buffer.Length);
- }
-
- public void Write (byte[] buffer, int start, int size)
- {
- _stream.Write (buffer, start, size);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs
deleted file mode 100644
index aa34db9d0..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class ReentrantLock
- {
- public void Lock ()
- {
- Monitor.Enter (this);
- }
-
- public bool TryLock ()
- {
- return Monitor.TryEnter (this);
- }
-
- public void Unlock ()
- {
- Monitor.Exit (this);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs
deleted file mode 100644
index c7fbe9a48..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal abstract class Reference<T>
- {
- public abstract T Get ();
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs
deleted file mode 100644
index 74ff16b1b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs
+++ /dev/null
@@ -1,212 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class Runtime
- {
- private static Runtime _instance;
- private List<ShutdownHook> _shutdownHooks = new List<ShutdownHook> ();
-
- internal void AddShutdownHook (IRunnable r)
- {
- ShutdownHook item = new ShutdownHook ();
- item.Runnable = r;
- _shutdownHooks.Add (item);
- }
-
- internal int AvailableProcessors ()
- {
- return Environment.ProcessorCount;
- }
-
- public static long CurrentTimeMillis ()
- {
- return DateTime.UtcNow.ToMillisecondsSinceEpoch ();
- }
-
- static Hashtable _properties;
-
- public static Hashtable GetProperties ()
- {
- if (_properties == null) {
- _properties = new Hashtable ();
- _properties ["jgit.fs.debug"] = "false";
- _properties["file.encoding"] = "UTF-8";
- if (Path.DirectorySeparatorChar != '\\')
- _properties ["os.name"] = "Unix";
- else
- _properties ["os.name"] = "Windows";
- }
- return _properties;
- }
-
- public static string GetProperty (string key)
- {
- if (GetProperties().Keys.Contains(key))
- {
- return ((string)GetProperties()[key]);
- }
- return null;
- }
-
- public static void SetProperty (string key, string value)
- {
- GetProperties () [key] = value;
- }
-
- public static Runtime GetRuntime ()
- {
- if (_instance == null) {
- _instance = new Runtime ();
- }
- return _instance;
- }
-
- public static int IdentityHashCode (object ob)
- {
- return RuntimeHelpers.GetHashCode (ob);
- }
-
- internal long MaxMemory ()
- {
- return int.MaxValue;
- }
-
- private class ShutdownHook
- {
- public IRunnable Runnable;
-
- ~ShutdownHook ()
- {
- Runnable.Run ();
- }
- }
-
- public static void DeleteCharAt (StringBuilder sb, int index)
- {
- sb.Remove (index, 1);
- }
-
- public static byte[] GetBytesForString (string str)
- {
- return Encoding.UTF8.GetBytes (str);
- }
-
- public static byte[] GetBytesForString (string str, string encoding)
- {
- return Encoding.GetEncoding (encoding).GetBytes (str);
- }
-
- public static FieldInfo[] GetDeclaredFields (Type t)
- {
- throw new NotImplementedException("Type.GetFields not found on .NetStandard");
- //return t.GetFields (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- }
-
- public static void NotifyAll (object ob)
- {
- Monitor.PulseAll (ob);
- }
-
- public static void Notify(object obj)
- {
- Monitor.Pulse(obj);
- }
-
- public static void PrintStackTrace (Exception ex)
- {
- Console.WriteLine (ex);
- }
-
- public static void PrintStackTrace (Exception ex, TextWriter tw)
- {
- tw.WriteLine (ex);
- }
-
- public static string Substring (string str, int index)
- {
- return str.Substring (index);
- }
-
- public static string Substring (string str, int index, int endIndex)
- {
- return str.Substring (index, endIndex - index);
- }
-
- public static void Wait (object ob)
- {
- Monitor.Wait (ob);
- }
-
- public static bool Wait (object ob, long milis)
- {
- return Monitor.Wait (ob, (int)milis);
- }
-
- public static Type GetType (string name)
- {
- throw new NotImplementedException("AppDomain.CurrentDomain.GetAssemblies not found on .NetStandard");
- //foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
- // Type t = a.GetType (name);
- // if (t != null)
- // return t;
- //}
- //never used
- //throw new InvalidOperationException ("Type not found: " + name);
- }
-
- public static void SetCharAt (StringBuilder sb, int index, char c)
- {
- sb [index] = c;
- }
-
- public static bool EqualsIgnoreCase (string s1, string s2)
- {
- return s1.Equals (s2, StringComparison.CurrentCultureIgnoreCase);
- }
-
- internal static long NanoTime ()
- {
- return Environment.TickCount * 1000 * 1000;
- }
-
- internal static int CompareOrdinal (string s1, string s2)
- {
- return string.CompareOrdinal (s1, s2);
- }
-
- public static string GetStringForBytes (byte[] chars)
- {
- return Encoding.UTF8.GetString (chars, 0, chars.Length);
- }
-
- public static string GetStringForBytes (byte[] chars, string encoding)
- {
- return GetEncoding (encoding).GetString (chars, 0, chars.Length);
- }
-
- public static string GetStringForBytes (byte[] chars, int start, int len)
- {
- return Encoding.UTF8.GetString (chars, start, len);
- }
-
- public static string GetStringForBytes (byte[] chars, int start, int len, string encoding)
- {
- return GetEncoding (encoding).Decode (chars, start, len);
- }
-
- public static Encoding GetEncoding (string name)
- {
- Encoding e = Encoding.GetEncoding (name.Replace ('_','-'));
- if (e is UTF8Encoding)
- return new UTF8Encoding (false, true);
- return e;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs
deleted file mode 100644
index 35334b4f2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System;
-using System.Globalization;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class SimpleDateFormat : DateFormat
- {
- string _format;
-
- CultureInfo Culture {
- get; set;
- }
-
- bool Lenient {
- get; set;
- }
-
- public SimpleDateFormat (): this ("g")
- {
- }
-
- public SimpleDateFormat (string format): this (format, CultureInfo.CurrentCulture)
- {
- }
-
- public SimpleDateFormat (string format, CultureInfo c)
- {
- Culture = c;
- this._format = format.Replace ("EEE", "ddd");
- this._format = this._format.Replace ("Z", "zzz");
- SetTimeZone (TimeZoneInfo.Local);
- }
-
- public bool IsLenient ()
- {
- return Lenient;
- }
-
- public void SetLenient (bool lenient)
- {
- Lenient = lenient;
- }
-
- public override DateTime Parse (string value)
- {
- if (IsLenient ())
- return DateTime.Parse (value);
- return DateTime.ParseExact (value, _format, Culture);
- }
-
- public override string Format (DateTime date)
- {
- date += GetTimeZone().BaseUtcOffset;
- return date.ToString (_format);
- }
-
- public string Format (long date)
- {
- return Extensions.MillisToDateTimeOffset (date, (int)GetTimeZone ().BaseUtcOffset.TotalMinutes).DateTime.ToString (_format);
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs
deleted file mode 100644
index 4d0651949..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-// SocketEx.cs implementation by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-using System;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class SocketEx : Socket
- {
- private int _soTimeOut = -1;
-
- public int SoTimeOut
- {
- get
- {
- return _soTimeOut;
- }
-
- set
- {
- if (value > 0)
- {
- _soTimeOut = value;
- }
- else
- {
- _soTimeOut = -1;
- }
-
- }
- }
-
- public SocketEx(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
- : base(addressFamily, socketType, protocolType)
- {
-
- }
-
- public void Connect(IPEndPoint endPoint, int timeOut)
- {
- using (var evt = new ManualResetEventSlim(false))
- {
- using (var args = new SocketAsyncEventArgs
- {
- RemoteEndPoint = endPoint
- })
- {
- args.Completed += delegate
- {
- evt.Set();
- };
-
- ConnectAsync(args);
-
- if (!evt.Wait(timeOut))
- {
- CancelConnectAsync(args);
- throw new ConnectException("Can't connect to end point.");
- }
- if (args.SocketError != SocketError.Success)
- {
- throw new ConnectException("Can't connect to end point.");
- }
- }
- }
- }
-
- public void Bind2(EndPoint ep)
- {
- if (ep == null)
- Bind(new IPEndPoint(IPAddress.Any, 0));
- else
- Bind(ep);
- }
-
-
- public int Receive(byte[] buffer, int offset, int count)
- {
- using (var evt = new ManualResetEventSlim(false))
- {
- using (var args = new SocketAsyncEventArgs
- {
- UserToken = this
- })
- {
- args.SetBuffer(buffer, offset, count);
-
- args.Completed += delegate
- {
- evt.Set();
- };
-
- if (ReceiveAsync(args))
- {
- if (!evt.Wait(_soTimeOut))
- {
- throw new TimeoutException("No data received.");
- }
- }
-
- return args.BytesTransferred;
- }
- }
- }
-
- public void Send(byte[] buffer, int offset, int length, EndPoint destination = null)
- {
- using (var evt = new ManualResetEventSlim(false))
- {
- using (SocketAsyncEventArgs args = new SocketAsyncEventArgs
- {
- UserToken = this
- })
- {
- args.SetBuffer(buffer, offset, length);
-
- args.Completed += delegate
- {
- evt.Set();
- };
-
- args.RemoteEndPoint = destination ?? RemoteEndPoint;
-
-
- SendToAsync(args);
- if (!evt.Wait(_soTimeOut))
- {
- throw new TimeoutException("No data sent.");
- }
- }
- }
- }
-
- public InputStream GetInputStream()
- {
- return new NetworkStream(this);
- }
-
- public OutputStream GetOutputStream()
- {
- return new NetworkStream(this);
- }
-
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs
deleted file mode 100644
index 74c14cff6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- public class StringTokenizer
- {
- private string[] _tokens;
- private int _pos;
-
- public StringTokenizer(string text, string delim)
- {
- _tokens = text.Split(delim);
- }
-
- public int CountTokens()
- {
- return _tokens.Length;
- }
-
- public string NextToken()
- {
- string value = _tokens[_pos];
-
- _pos++;
-
- return value;
- }
-
- public bool HasMoreTokens()
- {
- return _pos < _tokens.Length;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs
deleted file mode 100644
index c105a8bab..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using System.Collections;
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class SynchronizedList<T> : IList<T>
- {
- private IList<T> _list;
-
- public SynchronizedList (IList<T> list)
- {
- this._list = list;
- }
-
- public int IndexOf (T item)
- {
- lock (_list) {
- return _list.IndexOf (item);
- }
- }
-
- public void Insert (int index, T item)
- {
- lock (_list) {
- _list.Insert (index, item);
- }
- }
-
- public void RemoveAt (int index)
- {
- lock (_list) {
- _list.RemoveAt (index);
- }
- }
-
- void ICollection<T>.Add (T item)
- {
- lock (_list) {
- _list.Add (item);
- }
- }
-
- void ICollection<T>.Clear ()
- {
- lock (_list) {
- _list.Clear ();
- }
- }
-
- bool ICollection<T>.Contains (T item)
- {
- lock (_list) {
- return _list.Contains (item);
- }
- }
-
- void ICollection<T>.CopyTo (T[] array, int arrayIndex)
- {
- lock (_list) {
- _list.CopyTo (array, arrayIndex);
- }
- }
-
- bool ICollection<T>.Remove (T item)
- {
- lock (_list) {
- return _list.Remove (item);
- }
- }
-
- IEnumerator<T> IEnumerable<T>.GetEnumerator ()
- {
- return _list.GetEnumerator ();
- }
-
- IEnumerator IEnumerable.GetEnumerator ()
- {
- return _list.GetEnumerator ();
- }
-
- public T this[int index] {
- get {
- lock (_list) {
- return _list[index];
- }
- }
- set {
- lock (_list) {
- _list[index] = value;
- }
- }
- }
-
- int ICollection<T>.Count {
- get {
- lock (_list) {
- return _list.Count;
- }
- }
- }
-
- bool ICollection<T>.IsReadOnly {
- get { return _list.IsReadOnly; }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs
deleted file mode 100644
index 59f3df469..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs
+++ /dev/null
@@ -1,193 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace SharpCifs.Util.Sharpen
-{
- public class Thread : IRunnable
- {
- private static ThreadGroup _defaultGroup = new ThreadGroup ();
- private bool _interrupted;
- private IRunnable _runnable;
- private ThreadGroup _tgroup;
- private System.Threading.Thread _thread;
-
- [ThreadStatic]
- private static Thread _wrapperThread;
-
- public Thread () : this(null, null, null)
- {
- }
-
- public Thread (string name) : this (null, null, name)
- {
- }
-
- public Thread (ThreadGroup grp, string name) : this (null, grp, name)
- {
- }
-
- public Thread (IRunnable runnable): this (runnable, null, null)
- {
- }
-
- Thread (IRunnable runnable, ThreadGroup grp, string name)
- {
- _thread = new System.Threading.Thread (InternalRun);
-
- this._runnable = runnable ?? this;
- _tgroup = grp ?? _defaultGroup;
- _tgroup.Add (this);
- if (name != null)
- _thread.Name = name;
- }
-
- private Thread (System.Threading.Thread t)
- {
- _thread = t;
- _tgroup = _defaultGroup;
- _tgroup.Add (this);
- }
-
- public static Thread CurrentThread ()
- {
- if (_wrapperThread == null) {
- _wrapperThread = new Thread (System.Threading.Thread.CurrentThread);
- }
- return _wrapperThread;
- }
-
- public string GetName ()
- {
- return _thread.Name;
- }
-
- public ThreadGroup GetThreadGroup ()
- {
- return _tgroup;
- }
-
- private void InternalRun ()
- {
- _wrapperThread = this;
- try {
- _runnable.Run ();
- } catch (Exception exception) {
- Console.WriteLine (exception);
- } finally {
- _tgroup.Remove (this);
- }
- }
-
- public static void Yield ()
- {
- }
-
- public void Interrupt ()
- {
- lock (_thread) {
- _interrupted = true;
- //thread.Interrupt ();
-
- //TODO: implement CancellationToken
- //_thread.Abort();
- throw new NotImplementedException("implement CancellationToken for thread");
- }
- }
-
- public static bool Interrupted ()
- {
- if (Thread._wrapperThread == null) {
- return false;
- }
- Thread wrapperThread = Thread._wrapperThread;
- lock (wrapperThread) {
- bool interrupted = Thread._wrapperThread._interrupted;
- Thread._wrapperThread._interrupted = false;
- return interrupted;
- }
- }
-
- public bool IsAlive ()
- {
- return _thread.IsAlive;
- }
-
- public void Join ()
- {
- _thread.Join ();
- }
-
- public void Join (long timeout)
- {
- _thread.Join ((int)timeout);
- }
-
- public virtual void Run ()
- {
- }
-
- public void SetDaemon (bool daemon)
- {
- _thread.IsBackground = daemon;
- }
-
- public void SetName (string name)
- {
- _thread.Name = name;
- }
-
- public static void Sleep (long milis)
- {
- System.Threading.Thread.Sleep ((int)milis);
- }
-
- public void Start ()
- {
- _thread.Start ();
- }
-
- public void Abort ()
- {
- //TODO: implement CancellationToken
- //_thread.Abort ();
- throw new NotImplementedException("implement CancellationToken for thread");
- }
-
- }
-
- public class ThreadGroup
- {
- private List<Thread> _threads = new List<Thread> ();
-
- public ThreadGroup()
- {
- }
-
- public ThreadGroup (string name)
- {
- }
-
- internal void Add (Thread t)
- {
- lock (_threads) {
- _threads.Add (t);
- }
- }
-
- internal void Remove (Thread t)
- {
- lock (_threads) {
- _threads.Remove (t);
- }
- }
-
- public int Enumerate (Thread[] array)
- {
- lock (_threads) {
- int count = Math.Min (array.Length, _threads.Count);
- _threads.CopyTo (0, array, 0, count);
- return count;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs
deleted file mode 100644
index 7276c06a2..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace SharpCifs.Util.Sharpen
-{
- internal class ThreadFactory
- {
- public Thread NewThread (IRunnable r)
- {
- Thread t = new Thread (r);
- t.SetDaemon (true);
- t.Start ();
- return t;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs
deleted file mode 100644
index ef19b8bff..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs
+++ /dev/null
@@ -1,166 +0,0 @@
-using System;
-using System.Collections.Generic;
-using ST = System.Threading;
-
-namespace SharpCifs.Util.Sharpen
-{
- class ThreadPoolExecutor
- {
- ThreadFactory _tf;
- int _corePoolSize;
- int _maxPoolSize;
- List<Thread> _pool = new List<Thread> ();
- int _runningThreads;
- int _freeThreads;
- bool _shutdown;
- Queue<IRunnable> _pendingTasks = new Queue<IRunnable> ();
-
- public ThreadPoolExecutor (int corePoolSize, ThreadFactory factory)
- {
- this._corePoolSize = corePoolSize;
- _maxPoolSize = corePoolSize;
- _tf = factory;
- }
-
- public void SetMaximumPoolSize (int size)
- {
- _maxPoolSize = size;
- }
-
- public bool IsShutdown ()
- {
- return _shutdown;
- }
-
- public virtual bool IsTerminated ()
- {
- lock (_pendingTasks) {
- return _shutdown && _pendingTasks.Count == 0;
- }
- }
-
- public virtual bool IsTerminating ()
- {
- lock (_pendingTasks) {
- return _shutdown && !IsTerminated ();
- }
- }
-
- public int GetCorePoolSize ()
- {
- return _corePoolSize;
- }
-
- public void PrestartAllCoreThreads ()
- {
- lock (_pendingTasks) {
- while (_runningThreads < _corePoolSize)
- StartPoolThread ();
- }
- }
-
- public void SetThreadFactory (ThreadFactory f)
- {
- _tf = f;
- }
-
- public void Execute (IRunnable r)
- {
- InternalExecute (r, true);
- }
-
- internal void InternalExecute (IRunnable r, bool checkShutdown)
- {
- lock (_pendingTasks) {
- if (_shutdown && checkShutdown)
- throw new InvalidOperationException ();
- if (_runningThreads < _corePoolSize) {
- StartPoolThread ();
- }
- else if (_freeThreads > 0) {
- _freeThreads--;
- }
- else if (_runningThreads < _maxPoolSize) {
- StartPoolThread ();
- }
- _pendingTasks.Enqueue (r);
- ST.Monitor.PulseAll (_pendingTasks);
- }
- }
-
- void StartPoolThread ()
- {
- _runningThreads++;
- _pool.Add (_tf.NewThread (new RunnableAction (RunPoolThread)));
- }
-
- public void RunPoolThread ()
- {
- while (!IsTerminated ()) {
- try {
- IRunnable r = null;
- lock (_pendingTasks) {
- _freeThreads++;
- while (!IsTerminated () && _pendingTasks.Count == 0)
- ST.Monitor.Wait (_pendingTasks);
- if (IsTerminated ())
- break;
- r = _pendingTasks.Dequeue ();
- }
- if (r != null)
- r.Run ();
- }
- //supress all errors, anyway
- //catch (ST.ThreadAbortException) {
- // // Do not catch a thread abort. If we've been aborted just let the thread die.
- // // Currently reseting an abort which was issued because the appdomain is being
- // // torn down results in the process living forever and consuming 100% cpu time.
- // return;
- //}
- catch {
- }
- }
- }
-
- public virtual void Shutdown ()
- {
- lock (_pendingTasks) {
- _shutdown = true;
- ST.Monitor.PulseAll (_pendingTasks);
- }
- }
-
- public virtual List<IRunnable> ShutdownNow ()
- {
- lock (_pendingTasks) {
- _shutdown = true;
- foreach (var t in _pool) {
- try {
- t.Abort ();
- } catch {}
- }
- _pool.Clear ();
- _freeThreads = 0;
- _runningThreads = 0;
- var res = new List<IRunnable> (_pendingTasks);
- _pendingTasks.Clear ();
- return res;
- }
- }
- }
-
- class RunnableAction: IRunnable
- {
- Action _action;
-
- public RunnableAction (Action a)
- {
- _action = a;
- }
-
- public void Run ()
- {
- _action ();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs
deleted file mode 100644
index ef2993fa6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-using System;
-using System.IO;
-
-namespace SharpCifs.Util.Sharpen
-{
- internal class WrappedSystemStream : Stream
- {
- private InputStream _ist;
- private OutputStream _ost;
- int _position;
- int _markedPosition;
-
- public WrappedSystemStream (InputStream ist)
- {
- this._ist = ist;
- }
-
- public WrappedSystemStream (OutputStream ost)
- {
- this._ost = ost;
- }
-
- public InputStream InputStream {
- get { return _ist; }
- }
-
- public OutputStream OutputStream {
- get { return _ost; }
- }
-
- public void Close() //remove `override`
- {
- if (_ist != null) {
- //Stream.`Close` method deleted
- //_ist.Close ();
- _ist.Dispose();
- }
- if (_ost != null) {
- //Stream.`Close` method deleted
- //_ost.Close ();
- _ost.Dispose();
- }
- }
-
- public override void Flush ()
- {
- _ost.Flush ();
- }
-
- public override int Read (byte[] buffer, int offset, int count)
- {
- int res = _ist.Read (buffer, offset, count);
- if (res != -1) {
- _position += res;
- return res;
- }
- return 0;
- }
-
- public override int ReadByte ()
- {
- int res = _ist.Read ();
- if (res != -1)
- _position++;
- return res;
- }
-
- public override long Seek (long offset, SeekOrigin origin)
- {
- if (origin == SeekOrigin.Begin)
- Position = offset;
- else if (origin == SeekOrigin.Current)
- Position = Position + offset;
- else if (origin == SeekOrigin.End)
- Position = Length + offset;
- return Position;
- }
-
- public override void SetLength (long value)
- {
- throw new NotSupportedException ();
- }
-
- public override void Write (byte[] buffer, int offset, int count)
- {
- _ost.Write (buffer, offset, count);
- _position += count;
- }
-
- public override void WriteByte (byte value)
- {
- _ost.Write (value);
- _position++;
- }
-
- public override bool CanRead {
- get { return (_ist != null); }
- }
-
- public override bool CanSeek {
- get { return true; }
- }
-
- public override bool CanWrite {
- get { return (_ost != null); }
- }
-
- public override long Length {
- get { return _ist.Length; }
- }
-
- internal void OnMark (int nb)
- {
- _markedPosition = _position;
- _ist.Mark (nb);
- }
-
- public override long Position {
- get
- {
- if (_ist != null && _ist.CanSeek ())
- return _ist.Position;
- return _position;
- }
- set
- {
- if (value == _position)
- return;
- if (value == _markedPosition)
- _ist.Reset ();
- else if (_ist != null && _ist.CanSeek ()) {
- _ist.Position = value;
- }
- else
- throw new NotSupportedException ();
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs
deleted file mode 100644
index 6e0c3fc7b..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Util.Transport
-{
- public interface IRequest
- {
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs
deleted file mode 100644
index 702fea918..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-namespace SharpCifs.Util.Transport
-{
- public abstract class Response
- {
- public long Expiration;
-
- public bool IsReceived;
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs
deleted file mode 100644
index b02936ca6..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs
+++ /dev/null
@@ -1,454 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Smb;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util.Transport
-{
- /// <summary>
- /// This class simplifies communication for protocols that support
- /// multiplexing requests.
- /// </summary>
- /// <remarks>
- /// This class simplifies communication for protocols that support
- /// multiplexing requests. It encapsulates a stream and some protocol
- /// knowledge (provided by a concrete subclass) so that connecting,
- /// disconnecting, sending, and receiving can be syncronized
- /// properly. Apparatus is provided to send and receive requests
- /// concurrently.
- /// </remarks>
- public abstract class Transport : IRunnable
- {
- internal static int Id;
-
- //internal static LogStream log = LogStream.GetInstance();
-
- public LogStream Log
- {
- get
- {
- return LogStream.GetInstance();
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public static int Readn(InputStream @in, byte[] b, int off, int len)
- {
- int i = 0;
- int n = -5;
- while (i < len)
- {
- n = @in.Read(b, off + i, len - i);
- if (n <= 0)
- {
- break;
- }
- i += n;
- }
- return i;
- }
-
- internal int State;
-
- internal string Name = "Transport" + Id++;
-
- internal Thread Thread;
-
- internal TransportException Te;
-
- protected internal Hashtable ResponseMap = new Hashtable();
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void MakeKey(ServerMessageBlock request);
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract ServerMessageBlock PeekKey();
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoSend(ServerMessageBlock request);
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoRecv(Response response);
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoSkip();
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Sendrecv(ServerMessageBlock request, Response response, long timeout)
- {
- lock (this)
- {
- MakeKey(request);
- response.IsReceived = false;
- try
- {
- ResponseMap.Put(request, response);
- DoSend(request);
- response.Expiration = Runtime.CurrentTimeMillis() + timeout;
- while (!response.IsReceived)
- {
- Runtime.Wait(this, timeout);
- timeout = response.Expiration - Runtime.CurrentTimeMillis();
- if (timeout <= 0)
- {
- throw new TransportException(Name + " timedout waiting for response to " + request
- );
- }
- }
- }
- catch (IOException ioe)
- {
- if (Log.Level > 2)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- try
- {
- Disconnect(true);
- }
- catch (IOException ioe2)
- {
- Runtime.PrintStackTrace(ioe2, Log);
- }
- throw;
- }
- catch (Exception ie)
- {
- throw new TransportException(ie);
- }
- finally
- {
- //Sharpen.Collections.Remove(response_map, request);
- ResponseMap.Remove(request);
- }
- }
- }
-
- private void Loop()
- {
- while (Thread == Thread.CurrentThread())
- {
- try
- {
- ServerMessageBlock key = PeekKey();
- if (key == null)
- {
- throw new IOException("end of stream");
- }
-
-
- lock (this)
- {
- Response response = (Response)ResponseMap.Get(key);
- if (response == null)
- {
- if (Log.Level >= 4)
- {
- Log.WriteLine("Invalid key, skipping message");
- }
- DoSkip();
- }
- else
- {
- DoRecv(response);
- response.IsReceived = true;
- Runtime.NotifyAll(this);
- }
- }
- }
- catch (Exception ex)
- {
- string msg = ex.Message;
- bool timeout = msg != null && msg.Equals("Read timed out");
- bool hard = timeout == false;
- if (!timeout && Log.Level >= 3)
- {
- Runtime.PrintStackTrace(ex, Log);
- }
- try
- {
- Disconnect(hard);
- }
- catch (IOException ioe)
- {
- Runtime.PrintStackTrace(ioe, Log);
- }
- }
- }
- }
-
- /// <exception cref="System.Exception"></exception>
- protected internal abstract void DoConnect();
-
- /// <exception cref="System.IO.IOException"></exception>
- protected internal abstract void DoDisconnect(bool hard);
-
- /// <exception cref="SharpCifs.Util.Transport.TransportException"></exception>
- public virtual void Connect(long timeout)
- {
- lock (this)
- {
- try
- {
- switch (State)
- {
- case 0:
- {
- break;
- }
-
- case 3:
- {
- return;
- }
-
- case 4:
- {
- // already connected
- State = 0;
- throw new TransportException("Connection in error", Te);
- }
-
- default:
- {
- //TransportException te = new TransportException("Invalid state: " + state);
- State = 0;
- throw new TransportException("Invalid state: " + State);
- }
- }
- State = 1;
- Te = null;
- Thread = new Thread(this);
- Thread.SetDaemon(true);
- lock (Thread)
- {
- Thread.Start();
- Runtime.Wait(Thread, timeout);
- switch (State)
- {
- case 1:
- {
- State = 0;
- Thread = null;
- throw new TransportException("Connection timeout");
- }
-
- case 2:
- {
- if (Te != null)
- {
- State = 4;
- Thread = null;
- throw Te;
- }
- State = 3;
- return;
- }
- }
- }
- }
- catch (Exception ie)
- {
- State = 0;
- Thread = null;
- throw new TransportException(ie);
- }
- finally
- {
- if (State != 0 && State != 3 && State != 4)
- {
- if (Log.Level >= 1)
- {
- Log.WriteLine("Invalid state: " + State);
- }
- State = 0;
- Thread = null;
- }
- }
- }
- }
-
- /// <exception cref="System.IO.IOException"></exception>
- public virtual void Disconnect(bool hard)
- {
-
- if (hard)
- {
- IOException ioe = null;
- switch (State)
- {
- case 0:
- {
- return;
- }
-
- case 2:
- {
- hard = true;
- goto case 3;
- }
-
- case 3:
- {
- if (ResponseMap.Count != 0 && !hard)
- {
- break;
- }
- try
- {
- DoDisconnect(hard);
- }
- catch (IOException ioe0)
- {
- ioe = ioe0;
- }
- goto case 4;
- }
-
- case 4:
- {
- Thread = null;
- State = 0;
- break;
- }
-
- default:
- {
- if (Log.Level >= 1)
- {
- Log.WriteLine("Invalid state: " + State);
- }
- Thread = null;
- State = 0;
- break;
- }
- }
- if (ioe != null)
- {
- throw ioe;
- }
-
- return;
- }
-
- lock (this)
- {
- IOException ioe = null;
- switch (State)
- {
- case 0:
- {
- return;
- }
-
- case 2:
- {
- hard = true;
- goto case 3;
- }
-
- case 3:
- {
- if (ResponseMap.Count != 0 && !hard)
- {
- break;
- }
- try
- {
- DoDisconnect(hard);
- }
- catch (IOException ioe0)
- {
- ioe = ioe0;
- }
- goto case 4;
- }
-
- case 4:
- {
- Thread = null;
- State = 0;
- break;
- }
-
- default:
- {
- if (Log.Level >= 1)
- {
- Log.WriteLine("Invalid state: " + State);
- }
- Thread = null;
- State = 0;
- break;
- }
- }
- if (ioe != null)
- {
- throw ioe;
- }
- }
- }
-
- public virtual void Run()
- {
- Thread runThread = Thread.CurrentThread();
- Exception ex0 = null;
- try
- {
- DoConnect();
- }
- catch (Exception ex)
- {
- ex0 = ex;
- // Defer to below where we're locked
- return;
- }
- finally
- {
- lock (runThread)
- {
- if (runThread != Thread)
- {
- if (ex0 != null)
- {
- if (Log.Level >= 2)
- {
- Runtime.PrintStackTrace(ex0, Log);
- }
- }
- //return;
- }
- if (ex0 != null)
- {
- Te = new TransportException(ex0);
- }
- State = 2;
- // run connected
- Runtime.Notify(runThread);
- }
- }
- Loop();
- }
-
- public override string ToString()
- {
- return Name;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs
deleted file mode 100644
index bd0455197..000000000
--- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-// This code is derived from jcifs smb client library <jcifs at samba dot org>
-// Ported by J. Arturo <webmaster at komodosoft dot net>
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-using System;
-using System.IO;
-using SharpCifs.Util.Sharpen;
-
-namespace SharpCifs.Util.Transport
-{
-
- public class TransportException : IOException
- {
- private Exception _rootCause;
-
- public TransportException()
- {
- }
-
- public TransportException(string msg) : base(msg)
- {
- }
-
- public TransportException(Exception rootCause)
- {
- this._rootCause = rootCause;
- }
-
- public TransportException(string msg, Exception rootCause) : base(msg)
- {
- this._rootCause = rootCause;
- }
-
- public virtual Exception GetRootCause()
- {
- return _rootCause;
- }
-
- public override string ToString()
- {
- if (_rootCause != null)
- {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- Runtime.PrintStackTrace(_rootCause, pw);
- return base.ToString() + "\n" + sw;
- }
- return base.ToString();
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs b/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs
deleted file mode 100644
index a48543bc7..000000000
--- a/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs
+++ /dev/null
@@ -1,621 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using MediaBrowser.Model.IO;
-using SharpCifs.Smb;
-
-namespace Emby.Server.Implementations.IO
-{
- public class SharpCifsFileSystem
- {
- private readonly MediaBrowser.Model.System.OperatingSystem _operatingSystem;
-
- public SharpCifsFileSystem(MediaBrowser.Model.System.OperatingSystem operatingSystem)
- {
- _operatingSystem = operatingSystem;
- }
-
- public bool IsEnabledForPath(string path)
- {
- if (_operatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
- {
- return false;
- }
-
- return path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase) || IsUncPath(path);
- }
-
- public string NormalizePath(string path)
- {
- if (path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
- {
- return path;
- }
-
- if (IsUncPath(path))
- {
- return ConvertUncToSmb(path);
- }
-
- return path;
- }
-
- public string GetDirectoryName(string path)
- {
- var separator = GetDirectorySeparatorChar(path);
- var result = Path.GetDirectoryName(path);
-
- if (separator == '/')
- {
- result = result.Replace('\\', '/');
-
- if (result.StartsWith("smb:/", StringComparison.OrdinalIgnoreCase) && !result.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
- {
- result = result.Replace("smb:/", "smb://");
- }
- }
-
- return result;
- }
-
- public char GetDirectorySeparatorChar(string path)
- {
- if (path.IndexOf('/') != -1)
- {
- return '/';
- }
-
- return '\\';
- }
-
- public FileSystemMetadata GetFileSystemInfo(string path)
- {
- var file = CreateSmbFile(path);
- return ToMetadata(file);
- }
-
- public FileSystemMetadata GetFileInfo(string path)
- {
- var file = CreateSmbFile(path);
- return ToMetadata(file, false);
- }
-
- public FileSystemMetadata GetDirectoryInfo(string path)
- {
- var file = CreateSmbFile(path);
- return ToMetadata(file, true);
- }
-
- private bool IsUncPath(string path)
- {
- return path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase);
- }
-
- private string GetReturnPath(SmbFile file)
- {
- return file.GetCanonicalPath().TrimEnd('/');
- //return file.GetPath();
- }
-
- private string ConvertUncToSmb(string path)
- {
- if (IsUncPath(path))
- {
- path = path.Replace('\\', '/');
- path = "smb:" + path;
- }
- return path;
- }
-
- private string AddAuthentication(string path)
- {
- return path;
- }
-
- private SmbFile CreateSmbFile(string path)
- {
- path = ConvertUncToSmb(path);
- path = AddAuthentication(path);
-
- return new SmbFile(path);
- }
-
- DateTime baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
-
- private FileSystemMetadata ToMetadata(SmbFile info, bool? isDirectory = null)
- {
- var result = new FileSystemMetadata();
-
- result.Exists = info.Exists();
- result.FullName = GetReturnPath(info);
- result.Extension = Path.GetExtension(result.FullName);
- result.Name = info.GetName();
-
- if (result.Exists)
- {
- result.IsDirectory = info.IsDirectory();
-
- if (info.IsFile())
- {
- result.Length = info.Length();
- result.DirectoryName = info.GetParent();
- }
-
- result.CreationTimeUtc = baseDate.AddMilliseconds(info.CreateTime());
- result.LastWriteTimeUtc = baseDate.AddMilliseconds(info.GetLastModified());
- }
- else
- {
- if (isDirectory.HasValue)
- {
- result.IsDirectory = isDirectory.Value;
- }
- }
-
- return result;
- }
-
- public void SetHidden(string path, bool isHidden)
- {
- var file = CreateSmbFile(path);
- SetHidden(file, isHidden);
- }
-
- public void SetReadOnly(string path, bool isReadOnly)
- {
- var file = CreateSmbFile(path);
- SetReadOnly(file, isReadOnly);
- }
-
- public void SetAttributes(string path, bool isHidden, bool isReadOnly)
- {
- var file = CreateSmbFile(path);
- SetHidden(file, isHidden);
- SetReadOnly(file, isReadOnly);
- }
-
- private void SetHidden(SmbFile file, bool isHidden)
- {
- var isCurrentlyHidden = file.IsHidden();
-
- if (isCurrentlyHidden && !isHidden)
- {
- file.SetAttributes(file.GetAttributes() & ~SmbFile.AttrHidden);
- }
- else if (!isCurrentlyHidden && isHidden)
- {
- file.SetAttributes(file.GetAttributes() | SmbFile.AttrHidden);
- }
- }
-
- private void SetReadOnly(SmbFile file, bool isReadOnly)
- {
- var isCurrentlyReadOnly = !file.CanWrite();
-
- if (isCurrentlyReadOnly && !isReadOnly)
- {
- file.SetReadWrite();
- }
- else if (!isCurrentlyReadOnly && isReadOnly)
- {
- file.SetReadOnly();
- }
- }
-
- public void DeleteFile(string path)
- {
- var file = CreateSmbFile(path);
-
- AssertFileExists(file, path);
-
- file.Delete();
- }
-
- public void DeleteDirectory(string path, bool recursive)
- {
- var file = CreateSmbFile(path);
-
- AssertDirectoryExists(file, path);
-
- file.Delete();
- }
-
- public void CreateDirectory(string path)
- {
- }
-
- public string[] ReadAllLines(string path)
- {
- var lines = new List<string>();
-
- using (var stream = OpenRead(path))
- {
- using (var reader = new StreamReader(stream))
- {
- while (!reader.EndOfStream)
- {
- lines.Add(reader.ReadLine());
- }
- }
- }
-
- return lines.ToArray();
- }
-
- public void WriteAllLines(string path, IEnumerable<string> lines)
- {
- using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- using (var writer = new StreamWriter(stream))
- {
- foreach (var line in lines)
- {
- writer.WriteLine(line);
- }
- }
- }
- }
-
- private void AssertFileExists(SmbFile file, string path)
- {
- if (!file.Exists())
- {
- throw new FileNotFoundException("File not found.", path);
- }
- }
-
- private void AssertDirectoryExists(SmbFile file, string path)
- {
- if (!file.Exists())
- {
- throw new FileNotFoundException("File not found.", path);
- }
- }
-
- public Stream OpenRead(string path)
- {
- var file = CreateSmbFile(path);
-
- AssertFileExists(file, path);
-
- return file.GetInputStream();
- }
-
- private Stream OpenWrite(string path)
- {
- var file = CreateSmbFile(path);
-
- AssertFileExists(file, path);
-
- return file.GetInputStream();
- }
-
- public void CopyFile(string source, string target, bool overwrite)
- {
- if (string.Equals(source, target, StringComparison.Ordinal))
- {
- throw new ArgumentException("Cannot CopyFile when source and target are the same");
- }
-
- using (var input = OpenRead(source))
- {
- using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- input.CopyTo(output);
- }
- }
- }
-
- public void MoveFile(string source, string target)
- {
- if (string.Equals(source, target, StringComparison.Ordinal))
- {
- throw new ArgumentException("Cannot MoveFile when source and target are the same");
- }
-
- using (var input = OpenRead(source))
- {
- using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- input.CopyTo(output);
- }
- }
-
- DeleteFile(source);
- }
-
- public void MoveDirectory(string source, string target)
- {
- throw new NotImplementedException();
- }
-
- public bool DirectoryExists(string path)
- {
- var dir = CreateSmbFile(path);
-
- return dir.Exists() && dir.IsDirectory();
- }
-
- public bool FileExists(string path)
- {
- var file = CreateSmbFile(path);
- return file.Exists();
- }
-
- public string ReadAllText(string path, Encoding encoding)
- {
- using (var stream = OpenRead(path))
- {
- using (var reader = new StreamReader(stream, encoding))
- {
- return reader.ReadToEnd();
- }
- }
- }
-
- public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share)
- {
- if (mode == FileOpenMode.OpenOrCreate)
- {
- var file = CreateSmbFile(path);
- if (!file.Exists())
- {
- file.CreateNewFile();
- }
-
- mode = FileOpenMode.Open;
- }
-
- if (mode == FileOpenMode.CreateNew)
- {
- var file = CreateSmbFile(path);
- if (file.Exists())
- {
- throw new IOException("File already exists");
- }
-
- file.CreateNewFile();
-
- mode = FileOpenMode.Open;
- }
-
- if (mode == FileOpenMode.Create)
- {
- var file = CreateSmbFile(path);
- if (file.Exists())
- {
- if (file.IsHidden())
- {
- throw new UnauthorizedAccessException(string.Format("File {0} already exists and is hidden", path));
- }
-
- file.Delete();
- file.CreateNewFile();
- }
- else
- {
- file.CreateNewFile();
- }
-
- mode = FileOpenMode.Open;
- }
-
- if (mode == FileOpenMode.Open)
- {
- if (access == FileAccessMode.Read)
- {
- return OpenRead(path);
- }
- if (access == FileAccessMode.Write)
- {
- return OpenWrite(path);
- }
- throw new NotImplementedException();
- }
- throw new NotImplementedException();
- }
-
- public void WriteAllBytes(string path, byte[] bytes)
- {
- using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- stream.Write(bytes, 0, bytes.Length);
- }
- }
-
- public void WriteAllText(string path, string text)
- {
- using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- using (var writer = new StreamWriter(stream))
- {
- writer.Write(text);
- }
- }
- }
-
- public void WriteAllText(string path, string text, Encoding encoding)
- {
- using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
- {
- using (var writer = new StreamWriter(stream, encoding))
- {
- writer.Write(text);
- }
- }
- }
-
- public string ReadAllText(string path)
- {
- using (var stream = OpenRead(path))
- {
- using (var reader = new StreamReader(stream))
- {
- return reader.ReadToEnd();
- }
- }
- }
-
- public byte[] ReadAllBytes(string path)
- {
- using (var stream = OpenRead(path))
- {
- using (var ms = new MemoryStream())
- {
- stream.CopyTo(ms);
- ms.Position = 0;
- return ms.ToArray();
- }
- }
- }
-
- private SmbFile CreateSmbDirectoryForListFiles(string path)
- {
- // In order to call ListFiles, it has to end with the separator
-
- return CreateSmbFile(path.TrimEnd('/') + '/');
- }
-
- public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
- {
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
- var result = new List<FileSystemMetadata>();
-
- foreach (var file in list)
- {
- if (file.IsDirectory())
- {
- result.Add(ToMetadata(file));
- }
- }
-
- return result;
- }
-
- public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
- {
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
- var result = new List<FileSystemMetadata>();
-
- foreach (var file in list)
- {
- if (file.IsFile())
- {
- var filePath = GetReturnPath(file);
- var extension = Path.GetExtension(filePath);
-
- if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- result.Add(ToMetadata(file));
- }
- }
- }
-
- return result;
- }
-
- public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
- {
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
- var result = new List<FileSystemMetadata>();
-
- foreach (var file in list)
- {
- result.Add(ToMetadata(file));
- }
-
- return result;
- }
-
- public List<string> GetFileSystemEntryPaths(string path, bool recursive = false)
- {
- var result = new List<string>();
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
-
- foreach (var file in list)
- {
- result.Add(GetReturnPath(file));
- }
- return result;
- }
-
- public List<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
- {
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
- var result = new List<string>();
-
- foreach (var file in list)
- {
- if (file.IsFile())
- {
- var filePath = GetReturnPath(file);
- var extension = Path.GetExtension(filePath);
-
- if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- result.Add(filePath);
- }
- }
- }
-
- return result;
- }
-
- public List<string> GetDirectoryPaths(string path, bool recursive = false)
- {
- var dir = CreateSmbDirectoryForListFiles(path);
- AssertDirectoryExists(dir, path);
-
- var list = ListFiles(dir, recursive);
- var result = new List<string>();
-
- foreach (var file in list)
- {
- if (file.IsDirectory())
- {
- result.Add(GetReturnPath(file));
- }
- }
-
- return result;
- }
-
- private IEnumerable<SmbFile> ListFiles(SmbFile dir, bool recursive)
- {
- var list = dir.ListFiles();
- var result = new List<SmbFile>();
-
- foreach (var file in list)
- {
- result.Add(file);
-
- if (recursive && file.IsDirectory())
- {
- foreach (var subFile in ListFiles(file, recursive))
- {
- result.Add(subFile);
- }
- }
- }
-
- return result;
- }
- }
-}
diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs
index 48a5063e8..e91817611 100644
--- a/Emby.Server.Implementations/IO/StreamHelper.cs
+++ b/Emby.Server.Implementations/IO/StreamHelper.cs
@@ -163,7 +163,7 @@ namespace Emby.Server.Implementations.IO
var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
//var position = fs.Position;
- //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
+ //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
if (bytesRead == 0)
{
diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
index 59f0a9fc9..7fb979d66 100644
--- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
+++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
@@ -9,7 +9,7 @@ using System.Linq;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library
{
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index bd823e0c1..451f16bef 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -12,7 +12,7 @@ using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using Emby.Naming.Audio;
using Emby.Naming.Common;
@@ -351,7 +351,7 @@ namespace Emby.Server.Implementations.Library
if (item is LiveTvProgram)
{
- _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ _logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -359,7 +359,7 @@ namespace Emby.Server.Implementations.Library
}
else
{
- _logger.Info("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+ _logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Library
foreach (var metadataPath in GetMetadataPaths(item, children))
{
- _logger.Debug("Deleting path {0}", metadataPath);
+ _logger.LogDebug("Deleting path {0}", metadataPath);
try
{
@@ -384,7 +384,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error deleting {0}", ex, metadataPath);
+ _logger.LogError(ex, "Error deleting {metadataPath}", metadataPath);
}
}
@@ -398,14 +398,13 @@ namespace Emby.Server.Implementations.Library
{
try
{
+ _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName);
if (fileSystemInfo.IsDirectory)
{
- _logger.Debug("Deleting path {0}", fileSystemInfo.FullName);
_fileSystem.DeleteDirectory(fileSystemInfo.FullName, true);
}
else
{
- _logger.Debug("Deleting path {0}", fileSystemInfo.FullName);
_fileSystem.DeleteFile(fileSystemInfo.FullName);
}
}
@@ -489,7 +488,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path);
+ _logger.LogError(ex, "Error in {resolver} resolving {path}", resolver.GetType().Name, args.Path);
return null;
}
}
@@ -587,7 +586,7 @@ namespace Emby.Server.Implementations.Library
{
if (parent != null && parent.IsPhysicalRoot)
{
- _logger.ErrorException("Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", ex, isPhysicalRoot, isVf);
+ _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
files = new FileSystemMetadata[] { };
}
@@ -639,7 +638,7 @@ namespace Emby.Server.Implementations.Library
foreach (var dupe in dupes)
{
- _logger.Info("Found duplicate path: {0}", dupe);
+ _logger.LogInformation("Found duplicate path: {0}", dupe);
}
var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList();
@@ -713,7 +712,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
+ _logger.LogError(ex, "Error resolving path {path}", f.FullName);
return null;
}
}).Where(i => i != null);
@@ -735,7 +734,7 @@ namespace Emby.Server.Implementations.Library
// In case program data folder was moved
if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
{
- _logger.Info("Resetting root folder path to {0}", rootFolderPath);
+ _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
rootFolder.Path = rootFolderPath;
}
@@ -805,7 +804,7 @@ namespace Emby.Server.Implementations.Library
// In case program data folder was moved
if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
{
- _logger.Info("Resetting user root folder path to {0}", userRootPath);
+ _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
tmpItem.Path = userRootPath;
}
@@ -827,7 +826,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException("path");
}
- //_logger.Info("FindByPath {0}", path);
+ //_logger.LogInformation("FindByPath {0}", path);
var query = new InternalItemsQuery
{
@@ -1065,11 +1064,11 @@ namespace Emby.Server.Implementations.Library
await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
// Start by just validating the children of the root, but go no further
- await RootFolder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false);
+ await RootFolder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false);
await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
- await GetUserRootFolder().ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false).ConfigureAwait(false);
+ await GetUserRootFolder().ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false);
// Quickly scan CollectionFolders for changes
foreach (var folder in GetUserRootFolder().Children.OfType<Folder>().ToList())
@@ -1080,7 +1079,7 @@ namespace Emby.Server.Implementations.Library
private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
{
- _logger.Info("Validating media library");
+ _logger.LogInformation("Validating media library");
await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
@@ -1089,7 +1088,7 @@ namespace Emby.Server.Implementations.Library
innerProgress.RegisterAction(pct => progress.Report(pct * .96));
// Now validate the entire media library
- await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: true).ConfigureAwait(false);
+ await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: true).ConfigureAwait(false);
progress.Report(96);
@@ -1135,7 +1134,7 @@ namespace Emby.Server.Implementations.Library
progress.Report(innerPercent);
});
- _logger.Debug("Running post-scan task {0}", task.GetType().Name);
+ _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
try
{
@@ -1143,12 +1142,12 @@ namespace Emby.Server.Implementations.Library
}
catch (OperationCanceledException)
{
- _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
+ _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
throw;
}
catch (Exception ex)
{
- _logger.ErrorException("Error running postscan task", ex);
+ _logger.LogError(ex, "Error running postscan task");
}
numComplete++;
@@ -1199,7 +1198,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error resolving shortcut file {0}", ex, i);
+ _logger.LogError(ex, "Error resolving shortcut file {file}", i);
return null;
}
})
@@ -1262,7 +1261,7 @@ namespace Emby.Server.Implementations.Library
item = RetrieveItem(id);
- //_logger.Debug("GetitemById {0}", id);
+ //_logger.LogDebug("GetitemById {0}", id);
if (item != null)
{
@@ -1440,7 +1439,7 @@ namespace Emby.Server.Implementations.Library
return true;
}
- //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name);
+ //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
return false;
}))
@@ -1506,7 +1505,7 @@ namespace Emby.Server.Implementations.Library
return true;
}
- //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name);
+ //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
return false;
}))
@@ -1650,7 +1649,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting intros", ex);
+ _logger.LogError(ex, "Error getting intros");
return new List<IntroInfo>();
}
@@ -1670,7 +1669,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting intro files", ex);
+ _logger.LogError(ex, "Error getting intro files");
return new List<string>();
}
@@ -1693,7 +1692,7 @@ namespace Emby.Server.Implementations.Library
if (video == null)
{
- _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
+ _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
}
}
else if (!string.IsNullOrEmpty(info.Path))
@@ -1705,7 +1704,7 @@ namespace Emby.Server.Implementations.Library
if (video == null)
{
- _logger.Error("Intro resolver returned null for {0}.", info.Path);
+ _logger.LogError("Intro resolver returned null for {path}.", info.Path);
}
else
{
@@ -1724,12 +1723,12 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
+ _logger.LogError(ex, "Error resolving path {path}.", info.Path);
}
}
else
{
- _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
+ _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
}
return video;
@@ -1873,7 +1872,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error in ItemAdded event handler", ex);
+ _logger.LogError(ex, "Error in ItemAdded event handler");
}
}
}
@@ -1904,7 +1903,7 @@ namespace Emby.Server.Implementations.Library
}
//var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
- //_logger.Debug("Saving {0} to database.", logName);
+ //_logger.LogDebug("Saving {0} to database.", logName);
ItemRepository.SaveItems(items, cancellationToken);
@@ -1929,7 +1928,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error in ItemUpdated event handler", ex);
+ _logger.LogError(ex, "Error in ItemUpdated event handler");
}
}
}
@@ -1965,7 +1964,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error in ItemRemoved event handler", ex);
+ _logger.LogError(ex, "Error in ItemRemoved event handler");
}
}
}
@@ -2176,7 +2175,7 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None);
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal);
+ _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal);
}
return item;
@@ -2231,7 +2230,7 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
@@ -2295,7 +2294,7 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
@@ -2369,7 +2368,7 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
- _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
@@ -2808,7 +2807,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting person", ex);
+ _logger.LogError(ex, "Error getting person");
return null;
}
@@ -2836,7 +2835,7 @@ namespace Emby.Server.Implementations.Library
{
try
{
- _logger.Debug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
+ _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
await _providerManagerFactory().SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
index e027e133f..d0b3152ba 100644
--- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs
+++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System.Collections.Generic;
using MediaBrowser.Model.Serialization;
@@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.Library
{
mediaInfo = _json.DeserializeFromFile<MediaInfo>(cacheFilePath);
- //_logger.Debug("Found cached media info");
+ //_logger.LogDebug("Found cached media info");
}
catch
{
@@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Library
delayMs = Math.Max(3000, delayMs);
if (delayMs > 0)
{
- _logger.Info("Waiting {0}ms before probing the live stream", delayMs);
+ _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs);
await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
}
}
@@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Library
Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
_json.SerializeToFile(mediaInfo, cacheFilePath);
- //_logger.Debug("Saved media info to {0}", cacheFilePath);
+ //_logger.LogDebug("Saved media info to {0}", cacheFilePath);
}
}
@@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.Library
mediaStreams = newList;
}
- _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
+ _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
mediaSource.Bitrate = mediaInfo.Bitrate;
mediaSource.Container = mediaInfo.Container;
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index 0dc436800..ddda4b2c3 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -4,9 +4,10 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -127,7 +128,7 @@ namespace Emby.Server.Implementations.Library
if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video))
{
- await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(_fileSystem)
+ await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
EnableRemoteContentProbe = true,
MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh
@@ -159,9 +160,9 @@ namespace Emby.Server.Implementations.Library
list.Add(source);
}
- foreach (var source in list)
+ if (user != null)
{
- if (user != null)
+ foreach (var source in list)
{
if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
{
@@ -255,7 +256,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting media sources", ex);
+ _logger.LogError(ex, "Error getting media sources");
return new List<MediaSourceInfo>();
}
}
@@ -476,12 +477,12 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error probing live tv stream", ex);
+ _logger.LogError(ex, "Error probing live tv stream");
AddMediaInfo(mediaSource, isAudio);
}
var json = _jsonSerializer.SerializeToString(mediaSource);
- _logger.Info("Live stream opened: " + json);
+ _logger.LogInformation("Live stream opened: " + json);
var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
if (!request.UserId.Equals(Guid.Empty))
@@ -624,7 +625,7 @@ namespace Emby.Server.Implementations.Library
{
mediaInfo = _jsonSerializer.DeserializeFromFile<MediaInfo>(cacheFilePath);
- //_logger.Debug("Found cached media info");
+ //_logger.LogDebug("Found cached media info");
}
catch (Exception ex)
{
@@ -658,7 +659,7 @@ namespace Emby.Server.Implementations.Library
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath));
_jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath);
- //_logger.Debug("Saved media info to {0}", cacheFilePath);
+ //_logger.LogDebug("Saved media info to {0}", cacheFilePath);
}
}
@@ -679,7 +680,7 @@ namespace Emby.Server.Implementations.Library
mediaStreams = newList;
}
- _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
+ _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
mediaSource.Bitrate = mediaInfo.Bitrate;
mediaSource.Container = mediaInfo.Container;
@@ -815,16 +816,16 @@ namespace Emby.Server.Implementations.Library
{
liveStream.ConsumerCount--;
- _logger.Info("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount);
+ _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount);
if (liveStream.ConsumerCount <= 0)
{
_openStreams.Remove(id);
- _logger.Info("Closing live stream {0}", id);
+ _logger.LogInformation("Closing live stream {0}", id);
await liveStream.Close().ConfigureAwait(false);
- _logger.Info("Live stream {0} closed successfully", id);
+ _logger.LogInformation("Live stream {0} closed successfully", id);
}
}
}
@@ -883,4 +884,4 @@ namespace Emby.Server.Implementations.Library
}
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
index a33f101ae..dbfcf41e8 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using Emby.Naming.Audio;
using System;
using System.Collections.Generic;
@@ -128,7 +128,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
{
if (IsMultiDiscFolder(path, libraryOptions))
{
- logger.Debug("Found multi-disc folder: " + path);
+ logger.LogDebug("Found multi-disc folder: " + path);
discSubfolderCount++;
}
else
diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
index 2ad839673..71ccd7da8 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
index 556748183..143af4076 100644
--- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs
@@ -7,7 +7,7 @@ using System.IO;
using System.Linq;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers
{
diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
index 1394e3858..68b6c57ae 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
@@ -14,7 +14,7 @@ using System.Linq;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
index d8343f7c6..0fe42fa73 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization;
using Emby.Naming.Common;
using Emby.Naming.TV;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Resolvers.TV
{
@@ -72,7 +72,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
{
if (episodeInfo.EpisodeNumber.HasValue && episodeInfo.SeasonNumber.HasValue)
{
- _logger.Debug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}",
+ _logger.LogDebug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}",
path,
episodeInfo.SeasonNumber.Value,
episodeInfo.EpisodeNumber.Value);
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
index 951f439c2..32e8b6120 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using Emby.Naming.Common;
using Emby.Naming.TV;
using System;
@@ -131,14 +131,14 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
{
//if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
//{
- // //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName);
+ // //logger.LogDebug("Igoring series file or folder marked hidden: {0}", child.FullName);
// continue;
//}
// Can't enforce this because files saved by Bitcasa are always marked System
//if ((attributes & FileAttributes.System) == FileAttributes.System)
//{
- // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName);
+ // logger.LogDebug("Igoring series subfolder marked system: {0}", child.FullName);
// continue;
//}
@@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
{
if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager))
{
- //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName);
+ //logger.LogDebug("{0} is a series because of season folder {1}.", path, child.FullName);
return true;
}
}
@@ -181,7 +181,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
}
}
- //logger.Debug("{0} is not a series folder.", path);
+ //logger.LogDebug("{0} is not a series folder.", path);
return false;
}
diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs
index a7db46ef2..1212ba549 100644
--- a/Emby.Server.Implementations/Library/SearchEngine.cs
+++ b/Emby.Server.Implementations/Library/SearchEngine.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Search;
using System;
@@ -23,12 +23,12 @@ namespace Emby.Server.Implementations.Library
private readonly IUserManager _userManager;
private readonly ILogger _logger;
- public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager)
+ public SearchEngine(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager)
{
_libraryManager = libraryManager;
_userManager = userManager;
- _logger = logManager.GetLogger("SearchEngine");
+ _logger = loggerFactory.CreateLogger("SearchEngine");
}
public QueryResult<SearchHintInfo> GetSearchHints(SearchQuery query)
diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs
index 3714a7544..27ba32c0c 100644
--- a/Emby.Server.Implementations/Library/UserDataManager.cs
+++ b/Emby.Server.Implementations/Library/UserDataManager.cs
@@ -1,17 +1,14 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
-using System.Threading.Tasks;
using MediaBrowser.Controller.Dto;
using System.Globalization;
@@ -32,10 +29,10 @@ namespace Emby.Server.Implementations.Library
private Func<IUserManager> _userManager;
- public UserDataManager(ILogManager logManager, IServerConfigurationManager config, Func<IUserManager> userManager)
+ public UserDataManager(ILoggerFactory loggerFactory, IServerConfigurationManager config, Func<IUserManager> userManager)
{
_config = config;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
_userManager = userManager;
}
@@ -77,15 +74,14 @@ namespace Emby.Server.Implementations.Library
var cacheKey = GetCacheKey(userId, item.Id);
_userData.AddOrUpdate(cacheKey, userData, (k, v) => userData);
- EventHelper.FireEventIfNotNull(UserDataSaved, this, new UserDataSaveEventArgs
+ UserDataSaved?.Invoke(this, new UserDataSaveEventArgs
{
Keys = keys,
UserData = userData,
SaveReason = reason,
UserId = user.Id,
Item = item
-
- }, _logger);
+ });
}
/// <summary>
diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs
index da80a4824..679116fc0 100644
--- a/Emby.Server.Implementations/Library/UserManager.cs
+++ b/Emby.Server.Implementations/Library/UserManager.cs
@@ -2,7 +2,6 @@
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Connect;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -15,7 +14,7 @@ using MediaBrowser.Model.Connect;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Users;
using System;
@@ -135,7 +134,7 @@ namespace Emby.Server.Implementations.Library
/// <param name="user">The user.</param>
private void OnUserUpdated(User user)
{
- EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
+ UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
}
#endregion
@@ -150,7 +149,7 @@ namespace Emby.Server.Implementations.Library
/// <param name="user">The user.</param>
private void OnUserDeleted(User user)
{
- EventHelper.FireEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
+ UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
}
#endregion
@@ -340,7 +339,7 @@ namespace Emby.Server.Implementations.Library
UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
}
- _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
+ _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
return success ? user : null;
}
@@ -392,7 +391,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error authenticating with provider {0}", ex, provider.Name);
+ _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
return false;
}
@@ -461,7 +460,7 @@ namespace Emby.Server.Implementations.Library
if (newValue >= maxCount)
{
- //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
+ //_logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
//user.Policy.IsDisabled = true;
//fireLockout = true;
@@ -471,10 +470,7 @@ namespace Emby.Server.Implementations.Library
if (fireLockout)
{
- if (UserLockedOut != null)
- {
- EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
- }
+ UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
}
}
}
@@ -575,7 +571,7 @@ namespace Emby.Server.Implementations.Library
catch (Exception ex)
{
// Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
- _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
+ _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
}
}
@@ -599,7 +595,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
+ _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
return null;
}
}
@@ -613,7 +609,7 @@ namespace Emby.Server.Implementations.Library
{
foreach (var user in Users)
{
- await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
+ await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
}
}
@@ -775,7 +771,7 @@ namespace Emby.Server.Implementations.Library
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting file {0}", ex, configPath);
+ _logger.LogError(ex, "Error deleting file {path}", configPath);
}
DeleteUserPolicy(user);
@@ -820,7 +816,7 @@ namespace Emby.Server.Implementations.Library
UpdateUser(user);
- EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
+ UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
}
public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
@@ -844,7 +840,7 @@ namespace Emby.Server.Implementations.Library
UpdateUser(user);
- EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
+ UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
}
/// <summary>
@@ -1045,7 +1041,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error reading policy file: {0}", ex, path);
+ _logger.LogError(ex, "Error reading policy file: {path}", path);
return GetDefaultPolicy(user);
}
@@ -1088,7 +1084,7 @@ namespace Emby.Server.Implementations.Library
if (fireEvent)
{
- EventHelper.FireEventIfNotNull(UserPolicyUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
+ UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
}
}
@@ -1109,7 +1105,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error deleting policy file", ex);
+ _logger.LogError(ex, "Error deleting policy file");
}
}
@@ -1144,7 +1140,7 @@ namespace Emby.Server.Implementations.Library
}
catch (Exception ex)
{
- _logger.ErrorException("Error reading policy file: {0}", ex, path);
+ _logger.LogError(ex, "Error reading policy file: {path}", path);
return new UserConfiguration();
}
@@ -1183,7 +1179,7 @@ namespace Emby.Server.Implementations.Library
if (fireEvent)
{
- EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
+ UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
}
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
index 4d718dbee..eee66c8ac 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
index cd2aab4c8..1686dc23c 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing {0}", ex, name);
+ _logger.LogError(ex, "Error refreshing {ArtistName}", name);
}
numComplete++;
@@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Library.Validators
continue;
}
- _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs
index ee6c4461c..ea1f2e552 100644
--- a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs
index f7fbb9331..070777475 100644
--- a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing {0}", ex, name);
+ _logger.LogError(ex, "Error refreshing {GenreName}", name);
}
numComplete++;
diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
index be46decfb..4f4133340 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
@@ -3,7 +3,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library.Validators
{
diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
index d71e77a9a..775cde299 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing {0}", ex, name);
+ _logger.LogError(ex, "Error refreshing {GenreName}", name);
}
numComplete++;
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
index cd4021548..edc6f3ad6 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
index 98d53c125..b5ed1c0e6 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing {0}", ex, name);
+ _logger.LogError(ex, "Error refreshing {GenreName}", name);
}
numComplete++;
diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
index 1f4e1de92..50c7cfbc6 100644
--- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.Library.Validators
var numPeople = people.Count;
- _logger.Debug("Will refresh {0} people", numPeople);
+ _logger.LogDebug("Will refresh {0} people", numPeople);
foreach (var person in people)
{
@@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Validators
{
var item = _libraryManager.GetPerson(person);
- var options = new MetadataRefreshOptions(_fileSystem)
+ var options = new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ImageRefreshMode = MetadataRefreshMode.ValidationOnly,
MetadataRefreshMode = MetadataRefreshMode.ValidationOnly
@@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error validating IBN entry {0}", ex, person);
+ _logger.LogError(ex, "Error validating IBN entry {person}", person);
}
// Update progress
@@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.Library.Validators
foreach (var item in deadEntities)
{
- _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
@@ -108,7 +108,7 @@ namespace Emby.Server.Implementations.Library.Validators
progress.Report(100);
- _logger.Info("People validation complete");
+ _logger.LogInformation("People validation complete");
}
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
index d23efb6d3..45747dda1 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
index f306309b3..1a5ebac54 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing {0}", ex, name);
+ _logger.LogError(ex, "Error refreshing {StudioName}", name);
}
numComplete++;
@@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.Library.Validators
foreach (var item in deadEntities)
{
- _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
index 0c7980ca0..327b0181a 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
@@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
onStarted();
- _logger.Info("Copying recording stream to file {0}", targetFile);
+ _logger.LogInformation("Copying recording stream to file {0}", targetFile);
// The media source is infinite so we need to handle stopping ourselves
var durationToken = new CancellationTokenSource(duration);
@@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false);
}
- _logger.Info("Recording completed to file {0}", targetFile);
+ _logger.LogInformation("Recording completed to file {0}", targetFile);
}
private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
@@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
{
- _logger.Info("Opened recording stream from tuner provider");
+ _logger.LogInformation("Opened recording stream from tuner provider");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile));
@@ -86,7 +86,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
onStarted();
- _logger.Info("Copying recording stream to file {0}", targetFile);
+ _logger.LogInformation("Copying recording stream to file {0}", targetFile);
// The media source if infinite so we need to handle stopping ourselves
var durationToken = new CancellationTokenSource(duration);
@@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- _logger.Info("Recording completed to file {0}", targetFile);
+ _logger.LogInformation("Recording completed to file {0}", targetFile);
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
index 167f2a84b..81a47bfea 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
@@ -1,9 +1,16 @@
-using MediaBrowser.Common;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Security;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
@@ -12,27 +19,15 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
using MediaBrowser.Model.IO;
-using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.System;
@@ -80,7 +75,23 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private readonly IStreamHelper _streamHelper;
- public EmbyTV(IServerApplicationHost appHost, IStreamHelper streamHelper, IMediaSourceManager mediaSourceManager, IAssemblyInfo assemblyInfo, ILogger logger, IJsonSerializer jsonSerializer, IPowerManagement powerManagement, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IMediaEncoder mediaEncoder, ITimerFactory timerFactory, IProcessFactory processFactory, ISystemEvents systemEvents)
+ public EmbyTV(IServerApplicationHost appHost,
+ IStreamHelper streamHelper,
+ IMediaSourceManager mediaSourceManager,
+ IAssemblyInfo assemblyInfo,
+ ILogger logger,
+ IJsonSerializer jsonSerializer,
+ IHttpClient httpClient,
+ IServerConfigurationManager config,
+ ILiveTvManager liveTvManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ ILibraryMonitor libraryMonitor,
+ IProviderManager providerManager,
+ IMediaEncoder mediaEncoder,
+ ITimerFactory timerFactory,
+ IProcessFactory processFactory,
+ ISystemEvents systemEvents)
{
Current = this;
@@ -102,7 +113,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_streamHelper = streamHelper;
_seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
- _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory, powerManagement);
+ _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory);
_timerProvider.TimerFired += _timerProvider_TimerFired;
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
@@ -170,7 +181,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error creating virtual folder", ex);
+ _logger.LogError(ex, "Error creating virtual folder");
}
pathsAdded.AddRange(pathsToCreate);
@@ -196,13 +207,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error creating recording folders", ex);
+ _logger.LogError(ex, "Error creating recording folders");
}
}
private async Task RemovePathFromLibrary(string path)
{
- _logger.Debug("Removing path from library: {0}", path);
+ _logger.LogDebug("Removing path from library: {0}", path);
var requiresRefresh = false;
var virtualFolders = _libraryManager.GetVirtualFolders()
@@ -224,7 +235,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error removing virtual folder", ex);
+ _logger.LogError(ex, "Error removing virtual folder");
}
}
else
@@ -236,14 +247,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error removing media path", ex);
+ _logger.LogError(ex, "Error removing media path");
}
}
}
if (requiresRefresh)
{
- _libraryManager.ValidateMediaLibrary(new SimpleProgress<Double>(), CancellationToken.None);
+ await _libraryManager.ValidateMediaLibrary(new SimpleProgress<Double>(), CancellationToken.None);
}
}
@@ -342,7 +353,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting channels", ex);
+ _logger.LogError(ex, "Error getting channels");
}
}
@@ -364,7 +375,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error adding metadata", ex);
+ _logger.LogError(ex, "Error adding metadata");
}
}
}
@@ -406,7 +417,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
foreach (var channel in channels)
{
- _logger.Info("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
+ _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
}
result = new EpgChannelData(channels);
@@ -595,7 +606,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting channels", ex);
+ _logger.LogError(ex, "Error getting channels");
}
}
@@ -718,7 +729,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
if (programInfo == null)
{
- _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
+ _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
}
@@ -984,11 +995,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
{
- _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
+ _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
continue;
}
- _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
+ _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
@@ -996,7 +1007,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (epgChannel == null)
{
- _logger.Debug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
+ _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
programs = new List<ProgramInfo>();
}
else
@@ -1042,7 +1053,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public async Task<ILiveStream> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{
- _logger.Info("Streaming Channel " + channelId);
+ _logger.LogInformation("Streaming Channel " + channelId);
var result = string.IsNullOrEmpty(streamId) ?
null :
@@ -1052,7 +1063,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
result.ConsumerCount++;
- _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
+ _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
return result;
}
@@ -1067,7 +1078,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
result.OriginalStreamId = streamId;
- _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
+ _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
return result;
}
@@ -1174,7 +1185,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var timer = e.Argument;
- _logger.Info("Recording timer fired for {0}.", timer.Name);
+ _logger.LogInformation("Recording timer fired for {0}.", timer.Name);
try
{
@@ -1182,7 +1193,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (recordingEndDate <= DateTime.UtcNow)
{
- _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
+ _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
OnTimerOutOfDate(timer);
return;
}
@@ -1190,7 +1201,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false);
if (!registration.IsValid)
{
- _logger.Warn("Emby Premiere required to use Emby DVR.");
+ _logger.LogWarning("Emby Premiere required to use Emby DVR.");
OnTimerOutOfDate(timer);
return;
}
@@ -1208,7 +1219,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
else
{
- _logger.Info("Skipping RecordStream because it's already in progress.");
+ _logger.LogInformation("Skipping RecordStream because it's already in progress.");
}
}
catch (OperationCanceledException)
@@ -1217,7 +1228,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error recording stream", ex);
+ _logger.LogError(ex, "Error recording stream");
}
}
@@ -1342,7 +1353,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
if (programInfo == null)
{
- _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
+ _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
}
@@ -1390,9 +1401,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var duration = recordingEndDate - DateTime.UtcNow;
- _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
- _logger.Info("Writing file to path: " + recordPath);
+ _logger.LogInformation("Writing file to path: " + recordPath);
Action onStarted = async () =>
{
@@ -1414,16 +1425,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
recordingStatus = RecordingStatus.Completed;
- _logger.Info("Recording completed: {0}", recordPath);
+ _logger.LogInformation("Recording completed: {recordPath}", recordPath);
}
catch (OperationCanceledException)
{
- _logger.Info("Recording stopped: {0}", recordPath);
+ _logger.LogInformation("Recording stopped: {recordPath}", recordPath);
recordingStatus = RecordingStatus.Completed;
}
catch (Exception ex)
{
- _logger.ErrorException("Error recording to {0}", ex, recordPath);
+ _logger.LogError(ex, "Error recording to {recordPath}", recordPath);
recordingStatus = RecordingStatus.Error;
}
@@ -1435,7 +1446,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error closing live stream", ex);
+ _logger.LogError(ex, "Error closing live stream");
}
}
@@ -1450,7 +1461,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
{
const int retryIntervalSeconds = 60;
- _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
+ _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds);
timer.Status = RecordingStatus.New;
timer.PrePaddingSeconds = 0;
@@ -1511,22 +1522,22 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error deleting 0-byte failed recording file {0}", ex, path);
+ _logger.LogError(ex, "Error deleting 0-byte failed recording file {path}", path);
}
}
}
private void TriggerRefresh(string path)
{
- _logger.Info("Triggering refresh on {0}", path);
+ _logger.LogInformation("Triggering refresh on {path}", path);
var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path));
if (item != null)
{
- _logger.Info("Refreshing recording parent {0}", item.Path);
+ _logger.LogInformation("Refreshing recording parent {path}", item.Path);
- _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
RefreshPaths = new string[]
{
@@ -1642,7 +1653,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error deleting item", ex);
+ _logger.LogError(ex, "Error deleting item");
}
}
}
@@ -1668,7 +1679,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error deleting recording", ex);
+ _logger.LogError(ex, "Error deleting recording");
}
}
}
@@ -1773,14 +1784,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
UseShellExecute = false
});
- _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
process.Exited += Process_Exited;
process.Start();
}
catch (Exception ex)
{
- _logger.ErrorException("Error running recording post processor", ex);
+ _logger.LogError(ex, "Error running recording post processor");
}
}
@@ -1794,7 +1805,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var process = (IProcess)sender;
try
{
- _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
+ _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode);
}
catch
{
@@ -1875,7 +1886,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving recording image", ex);
+ _logger.LogError(ex, "Error saving recording image");
}
}
@@ -1890,7 +1901,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving recording image", ex);
+ _logger.LogError(ex, "Error saving recording image");
}
}
@@ -1903,7 +1914,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving recording image", ex);
+ _logger.LogError(ex, "Error saving recording image");
}
}
@@ -1916,7 +1927,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving recording image", ex);
+ _logger.LogError(ex, "Error saving recording image");
}
}
}
@@ -1984,7 +1995,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving nfo", ex);
+ _logger.LogError(ex, "Error saving nfo");
}
}
@@ -2790,7 +2801,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
{
- _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url);
+ _logger.LogInformation("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url);
configuredDevice.Url = device.Url;
await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
@@ -2807,14 +2818,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
foreach (var device in discoveredDevices)
{
- _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url);
+ _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url);
}
return discoveredDevices;
}
catch (Exception ex)
{
- _logger.ErrorException("Error discovering tuner devices", ex);
+ _logger.LogError(ex, "Error discovering tuner devices");
return new List<TunerHostInfo>();
}
@@ -2827,4 +2838,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
index 9506a82be..4ea83b7ac 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
@@ -8,7 +8,6 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
@@ -18,7 +17,7 @@ using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Library;
@@ -78,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
- _logger.Info("Recording completed to file {0}", targetFile);
+ _logger.LogInformation("Recording completed to file {0}", targetFile);
}
private EncodingOptions GetEncodingOptions()
@@ -112,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_process = process;
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
- _logger.Info(commandLineLogMessage);
+ _logger.LogInformation(commandLineLogMessage);
var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(logFilePath));
@@ -137,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
- _logger.Info("ffmpeg recording process started for {0}", _targetPath);
+ _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
return _taskCompletionSource.Task;
}
@@ -270,14 +269,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
try
{
- _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath);
+ _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
//process.Kill();
_process.StandardInput.WriteLine("q");
}
catch (Exception ex)
{
- _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath);
+ _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
}
if (_hasExited)
@@ -287,7 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
try
{
- _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath);
+ _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
if (_process.WaitForExit(10000))
{
@@ -296,7 +295,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath);
+ _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
}
if (_hasExited)
@@ -306,13 +305,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
try
{
- _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
+ _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
_process.Kill();
}
catch (Exception ex)
{
- _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath);
+ _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
}
}
}
@@ -330,7 +329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
var exitCode = process.ExitCode;
- _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
+ _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath);
if (exitCode == 0)
{
@@ -338,13 +337,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
else
{
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
+ _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode)));
}
}
catch
{
- _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
+ _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath);
+ _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath)));
}
}
@@ -358,7 +357,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing recording log stream", ex);
+ _logger.LogError(ex, "Error disposing recording log stream");
}
_logFileStream = null;
@@ -388,8 +387,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- _logger.ErrorException("Error reading ffmpeg recording log", ex);
+ _logger.LogError(ex, "Error reading ffmpeg recording log");
}
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
index 4ba2269a6..9f179dc2c 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
@@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (_items == null)
{
- Logger.Info("Loading live tv data from {0}", _dataPath);
+ Logger.LogInformation("Loading live tv data from {0}", _dataPath);
_items = GetItemsFromFile(_dataPath);
}
return _items.ToList();
@@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
catch (Exception ex)
{
- Logger.ErrorException("Error deserializing {0}", ex, jsonFile);
+ Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
}
return new List<T>();
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
index 63cd26c7e..620ba7650 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using MediaBrowser.Model.IO;
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
index b5f93b882..e4ab34770 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
@@ -1,19 +1,14 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Serialization;
-using System;
+using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Linq;
-using System.Threading;
-
-using MediaBrowser.Controller.IO;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Events;
+using Microsoft.Extensions.Logging;
+using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Threading;
-using MediaBrowser.Model.System;
namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
@@ -24,14 +19,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public event EventHandler<GenericEventArgs<TimerInfo>> TimerFired;
private readonly ITimerFactory _timerFactory;
- private readonly IPowerManagement _powerManagement;
- public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1, ITimerFactory timerFactory, IPowerManagement powerManagement)
+ public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1, ITimerFactory timerFactory)
: base(fileSystem, jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
{
_logger = logger1;
_timerFactory = timerFactory;
- _powerManagement = powerManagement;
}
public void RestartTimers()
@@ -40,7 +33,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
foreach (var item in GetAll().ToList())
{
- AddOrUpdateSystemTimer(item, false);
+ AddOrUpdateSystemTimer(item);
}
}
@@ -63,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public override void Update(TimerInfo item)
{
base.Update(item);
- AddOrUpdateSystemTimer(item, false);
+ AddOrUpdateSystemTimer(item);
}
public void AddOrUpdate(TimerInfo item, bool resetTimer)
@@ -94,7 +87,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
base.Add(item);
- AddOrUpdateSystemTimer(item, true);
+ AddOrUpdateSystemTimer(item);
}
private bool ShouldStartTimer(TimerInfo item)
@@ -108,7 +101,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return true;
}
- private void AddOrUpdateSystemTimer(TimerInfo item, bool scheduleSystemWakeTimer)
+ private void AddOrUpdateSystemTimer(TimerInfo item)
{
StopTimer(item);
@@ -122,29 +115,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (startDate < now)
{
- EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = item }, Logger);
+ TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = item });
return;
}
var dueTime = startDate - now;
StartTimer(item, dueTime);
-
- if (scheduleSystemWakeTimer && dueTime >= TimeSpan.FromMinutes(15))
- {
- ScheduleSystemWakeTimer(startDate, item.Name);
- }
- }
-
- private void ScheduleSystemWakeTimer(DateTime startDate, string displayName)
- {
- try
- {
- _powerManagement.ScheduleWake(startDate.AddMinutes(-5), displayName);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error scheduling wake timer", ex);
- }
}
private void StartTimer(TimerInfo item, TimeSpan dueTime)
@@ -153,12 +129,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (_timers.TryAdd(item.Id, timer))
{
- _logger.Info("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
}
else
{
timer.Dispose();
- _logger.Warn("Timer already exists for item {0}", item.Id);
+ _logger.LogWarning("Timer already exists for item {id}", item.Id);
}
}
@@ -178,7 +154,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase));
if (timer != null)
{
- EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = timer }, Logger);
+ TimerFired?.Invoke(this, new GenericEventArgs<TimerInfo> { Argument = timer });
}
}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
index 9021666a3..e8ffd0caa 100644
--- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using System;
@@ -16,8 +16,6 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.LiveTv.Listings
@@ -32,9 +30,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings
private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
- private readonly Dictionary<string, Dictionary<string, ScheduleDirect.Station>> _channelPairingCache =
- new Dictionary<string, Dictionary<string, ScheduleDirect.Station>>(StringComparer.OrdinalIgnoreCase);
-
public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
{
_logger = logger;
@@ -74,33 +69,29 @@ namespace Emby.Server.Implementations.LiveTv.Listings
// Normalize incoming input
channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
- List<ProgramInfo> programsInfo = new List<ProgramInfo>();
-
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(token))
{
- _logger.Warn("SchedulesDirect token is empty, returning empty program list");
- return programsInfo;
+ _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
+
+ return Enumerable.Empty<ProgramInfo>();
}
var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
- string stationID = channelId;
-
- _logger.Info("Channel Station ID is: " + stationID);
- List<ScheduleDirect.RequestScheduleForChannel> requestList =
- new List<ScheduleDirect.RequestScheduleForChannel>()
+ _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
+ var requestList = new List<ScheduleDirect.RequestScheduleForChannel>()
+ {
+ new ScheduleDirect.RequestScheduleForChannel()
{
- new ScheduleDirect.RequestScheduleForChannel()
- {
- stationID = stationID,
- date = dates
- }
- };
+ stationID = channelId,
+ date = dates
+ }
+ };
var requestString = _jsonSerializer.SerializeToString(requestList);
- _logger.Debug("Request string for schedules is: " + requestString);
+ _logger.LogDebug("Request string for schedules is: {RequestString}", requestString);
var httpOptions = new HttpRequestOptions()
{
@@ -109,18 +100,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings
CancellationToken = cancellationToken,
// The data can be large so give it some extra time
TimeoutMs = 60000,
- LogErrorResponseBody = true
+ LogErrorResponseBody = true,
+ RequestContent = requestString
};
httpOptions.RequestHeaders["token"] = token;
- httpOptions.RequestContent = requestString;
using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
+ using (StreamReader reader = new StreamReader(response.Content))
{
- StreamReader reader = new StreamReader(response.Content);
- string responseString = reader.ReadToEnd();
- var dailySchedules = _jsonSerializer.DeserializeFromString<List<ScheduleDirect.Day>>(responseString);
- _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect");
+ var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(response.Content).ConfigureAwait(false);
+ _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
httpOptions = new HttpRequestOptions()
{
@@ -134,22 +124,13 @@ namespace Emby.Server.Implementations.LiveTv.Listings
httpOptions.RequestHeaders["token"] = token;
- List<string> programsID = new List<string>();
- programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList();
- var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]";
- httpOptions.RequestContent = requestBody;
-
- double wideAspect = 1.77777778;
- var primaryImageCategory = "Logo";
+ var programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct();
+ httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]";
using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
+ using (StreamReader innerReader = new StreamReader(innerResponse.Content))
{
- StreamReader innerReader = new StreamReader(innerResponse.Content);
- responseString = innerReader.ReadToEnd();
-
- var programDetails =
- _jsonSerializer.DeserializeFromString<List<ScheduleDirect.ProgramDetails>>(
- responseString);
+ var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponse.Content).ConfigureAwait(false);
var programDict = programDetails.ToDictionary(p => p.programID, y => y);
var programIdsWithImages =
@@ -158,10 +139,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
- var schedules = dailySchedules.SelectMany(d => d.programs);
- foreach (ScheduleDirect.Program schedule in schedules)
+ List<ProgramInfo> programsInfo = new List<ProgramInfo>();
+ foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs))
{
- //_logger.Debug("Proccesing Schedule for statio ID " + stationID +
+ //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
// " which corresponds to channel " + channelNumber + " and program id " +
// schedule.programID + " which says it has images? " +
// programDict[schedule.programID].hasImageArtwork);
@@ -173,15 +154,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings
{
var programEntry = programDict[schedule.programID];
- var allImages = (images[imageIndex].data ?? new List<ScheduleDirect.ImageData>()).ToList();
- var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
- var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
+ var allImages = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>();
+ var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase));
+ var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase));
- double desiredAspect = 0.666666667;
+ const double desiredAspect = 0.666666667;
programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ??
GetProgramImage(ApiUrl, allImages, true, desiredAspect);
+ const double wideAspect = 1.77777778;
+
programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect);
// Don't supply the same image twice
@@ -201,18 +184,16 @@ namespace Emby.Server.Implementations.LiveTv.Listings
programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
}
+ return programsInfo;
}
}
-
- return programsInfo;
}
private int GetSizeOrder(ScheduleDirect.ImageData image)
{
if (!string.IsNullOrWhiteSpace(image.height))
{
- int value;
- if (int.TryParse(image.height, out value))
+ if (int.TryParse(image.height, out int value))
{
return value;
}
@@ -233,9 +214,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings
{
channelNumber = map.atscMajor + "." + map.atscMinor;
}
- channelNumber = channelNumber.TrimStart('0');
- return channelNumber;
+ return channelNumber.TrimStart('0');
}
private bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
@@ -390,8 +370,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
if (details.movie != null)
{
- int year;
- if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out year))
+ if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out int year))
{
info.ProductionYear = year;
}
@@ -422,18 +401,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return date;
}
- private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
+ private string GetProgramImage(string apiUrl, IEnumerable<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
{
- string url = null;
-
- var matches = images;
-
- matches = matches
- .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i)))
+ var match = images
+ .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
.ThenByDescending(GetSizeOrder)
- .ToList();
-
- var match = matches.FirstOrDefault();
+ .FirstOrDefault();
if (match == null)
{
@@ -442,22 +415,21 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var uri = match.uri;
- if (!string.IsNullOrWhiteSpace(uri))
+ if (string.IsNullOrWhiteSpace(uri))
{
- if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
- {
- url = uri;
- }
- else
- {
- url = apiUrl + "/image/" + uri;
- }
+ return null;
+ }
+ else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ return uri;
+ }
+ else
+ {
+ return apiUrl + "/image/" + uri;
}
- //_logger.Debug("URL for image is : " + url);
- return url;
}
- private double GetApsectRatio(ScheduleDirect.ImageData i)
+ private double GetAspectRatio(ScheduleDirect.ImageData i)
{
int width = 0;
int height = 0;
@@ -527,7 +499,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting image info from schedules direct", ex);
+ _logger.LogError(ex, "Error getting image info from schedules direct");
return new List<ScheduleDirect.ShowImages>();
}
@@ -557,35 +529,33 @@ namespace Emby.Server.Implementations.LiveTv.Listings
try
{
using (var httpResponse = await Get(options, false, info).ConfigureAwait(false))
+ using (Stream responce = httpResponse.Content)
{
- using (Stream responce = httpResponse.Content)
- {
- var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false);
+ var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false);
- if (root != null)
+ if (root != null)
+ {
+ foreach (ScheduleDirect.Headends headend in root)
{
- foreach (ScheduleDirect.Headends headend in root)
+ foreach (ScheduleDirect.Lineup lineup in headend.lineups)
{
- foreach (ScheduleDirect.Lineup lineup in headend.lineups)
+ lineups.Add(new NameIdPair
{
- lineups.Add(new NameIdPair
- {
- Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
- Id = lineup.uri.Substring(18)
- });
- }
+ Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
+ Id = lineup.uri.Substring(18)
+ });
}
}
- else
- {
- _logger.Info("No lineups available");
- }
+ }
+ else
+ {
+ _logger.LogInformation("No lineups available");
}
}
}
catch (Exception ex)
{
- _logger.Error("Error getting headends", ex);
+ _logger.LogError(ex, "Error getting headends");
}
return lineups;
@@ -624,8 +594,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
{
- long ticks;
- if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
+ if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
{
// If it's under 24 hours old we can still use it
if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
@@ -695,8 +664,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
- options.RequestHeaders["token"] = newToken;
+ options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);;
return await Post(options, false, providerInfo).ConfigureAwait(false);
}
@@ -734,8 +702,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
- var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
- options.RequestHeaders["token"] = newToken;
+ options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
return await Get(options, false, providerInfo).ConfigureAwait(false);
}
@@ -750,15 +717,15 @@ namespace Emby.Server.Implementations.LiveTv.Listings
CancellationToken = cancellationToken,
LogErrorResponseBody = true
};
- //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
+ //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
// httpOptions.RequestContent);
- using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false))
+ using (var response = await Post(httpOptions, false, null).ConfigureAwait(false))
{
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(responce.Content).ConfigureAwait(false);
+ var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(response.Content).ConfigureAwait(false);
if (root.message == "OK")
{
- _logger.Info("Authenticated with Schedules Direct token: " + root.token);
+ _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
return root.token;
}
@@ -780,7 +747,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
throw new ArgumentException("Listings Id required");
}
- _logger.Info("Adding new LineUp ");
+ _logger.LogInformation("Adding new LineUp ");
var httpOptions = new HttpRequestOptions()
{
@@ -823,7 +790,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
throw new Exception("token required");
}
- _logger.Info("Headends on account ");
+ _logger.LogInformation("Headends on account ");
var options = new HttpRequestOptions()
{
@@ -838,13 +805,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings
try
{
using (var httpResponse = await Get(options, false, null).ConfigureAwait(false))
+ using (var response = httpResponse.Content)
{
- using (var response = httpResponse.Content)
- {
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false);
+ var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false);
- return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
- }
+ return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
}
}
catch (HttpException ex)
@@ -923,54 +888,41 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var list = new List<ChannelInfo>();
using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false))
+ using (var response = httpResponse.Content)
{
- using (var response = httpResponse.Content)
- {
- var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false);
- _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect");
- _logger.Info("Mapping Stations to Channel");
-
- var allStations = root.stations ?? new List<ScheduleDirect.Station>();
-
- foreach (ScheduleDirect.Map map in root.map)
- {
- var channelNumber = GetChannelNumber(map);
+ var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false);
+ _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
+ _logger.LogInformation("Mapping Stations to Channel");
- var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
- if (station == null)
- {
- station = new ScheduleDirect.Station
- {
- stationID = map.stationID
- };
- }
+ var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>();
- var name = channelNumber;
+ foreach (ScheduleDirect.Map map in root.map)
+ {
+ var channelNumber = GetChannelNumber(map);
- var channelInfo = new ChannelInfo
+ var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
+ if (station == null)
+ {
+ station = new ScheduleDirect.Station
{
- Number = channelNumber,
- Name = name
+ stationID = map.stationID
};
+ }
- if (station != null)
- {
- if (!string.IsNullOrWhiteSpace(station.name))
- {
- channelInfo.Name = station.name;
- }
-
- channelInfo.Id = station.stationID;
- channelInfo.CallSign = station.callsign;
-
- if (station.logo != null)
- {
- channelInfo.ImageUrl = station.logo.URL;
- }
- }
+ var channelInfo = new ChannelInfo
+ {
+ Id = station.stationID,
+ CallSign = station.callsign,
+ Number = channelNumber,
+ Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
+ };
- list.Add(channelInfo);
+ if (station.logo != null)
+ {
+ channelInfo.ImageUrl = station.logo.URL;
}
+
+ list.Add(channelInfo);
}
}
@@ -1298,4 +1250,4 @@ namespace Emby.Server.Implementations.LiveTv.Listings
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
new file mode 100644
index 000000000..4d7c7fef4
--- /dev/null
+++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
@@ -0,0 +1,303 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Emby.XmlTv.Classes;
+using Emby.XmlTv.Entities;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Progress;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.LiveTv;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.LiveTv.Listings
+{
+ public class XmlTvListingsProvider : IListingsProvider
+ {
+ private readonly IServerConfigurationManager _config;
+ private readonly IHttpClient _httpClient;
+ private readonly ILogger _logger;
+ private readonly IFileSystem _fileSystem;
+ private readonly IZipClient _zipClient;
+
+ public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IFileSystem fileSystem, IZipClient zipClient)
+ {
+ _config = config;
+ _httpClient = httpClient;
+ _logger = logger;
+ _fileSystem = fileSystem;
+ _zipClient = zipClient;
+ }
+
+ public string Name
+ {
+ get { return "XmlTV"; }
+ }
+
+ public string Type
+ {
+ get { return "xmltv"; }
+ }
+
+ private string GetLanguage(ListingsProviderInfo info)
+ {
+ if (!string.IsNullOrWhiteSpace(info.PreferredLanguage))
+ {
+ return info.PreferredLanguage;
+ }
+
+ return _config.Configuration.PreferredMetadataLanguage;
+ }
+
+ private async Task<string> GetXml(string path, CancellationToken cancellationToken)
+ {
+ _logger.LogInformation("xmltv path: {path}", path);
+
+ if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
+ {
+ return UnzipIfNeeded(path, path);
+ }
+
+ string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml";
+ string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename);
+ if (_fileSystem.FileExists(cacheFile))
+ {
+ return UnzipIfNeeded(path, cacheFile);
+ }
+
+ _logger.LogInformation("Downloading xmltv listings from {path}", path);
+
+ string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
+ {
+ CancellationToken = cancellationToken,
+ Url = path,
+ Progress = new SimpleProgress<Double>(),
+ DecompressionMethod = CompressionMethod.Gzip,
+
+ // It's going to come back gzipped regardless of this value
+ // So we need to make sure the decompression method is set to gzip
+ EnableHttpCompression = true,
+
+ UserAgent = "Emby/3.0"
+
+ }).ConfigureAwait(false);
+
+ _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFile));
+
+ _fileSystem.CopyFile(tempFile, cacheFile, true);
+
+ return UnzipIfNeeded(path, cacheFile);
+ }
+
+ private string UnzipIfNeeded(string originalUrl, string file)
+ {
+ string ext = Path.GetExtension(originalUrl.Split('?')[0]);
+
+ if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase))
+ {
+ try
+ {
+ string tempFolder = ExtractGz(file);
+ return FindXmlFile(tempFolder);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error extracting from gz file {file}", file);
+ }
+
+ try
+ {
+ string tempFolder = ExtractFirstFileFromGz(file);
+ return FindXmlFile(tempFolder);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error extracting from zip file {file}", file);
+ }
+ }
+
+ return file;
+ }
+
+ private string ExtractFirstFileFromGz(string file)
+ {
+ using (var stream = _fileSystem.OpenRead(file))
+ {
+ string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
+ _fileSystem.CreateDirectory(tempFolder);
+
+ _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml");
+
+ return tempFolder;
+ }
+ }
+
+ private string ExtractGz(string file)
+ {
+ using (var stream = _fileSystem.OpenRead(file))
+ {
+ string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
+ _fileSystem.CreateDirectory(tempFolder);
+
+ _zipClient.ExtractAllFromGz(stream, tempFolder, true);
+
+ return tempFolder;
+ }
+ }
+
+ private string FindXmlFile(string directory)
+ {
+ return _fileSystem.GetFiles(directory, true)
+ .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
+ .Select(i => i.FullName)
+ .FirstOrDefault();
+ }
+
+ public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(channelId))
+ {
+ throw new ArgumentNullException("channelId");
+ }
+
+ /*
+ if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false))
+ {
+ var length = endDateUtc - startDateUtc;
+ if (length.TotalDays > 1)
+ {
+ endDateUtc = startDateUtc.AddDays(1);
+ }
+ }*/
+
+ _logger.LogDebug("Getting xmltv programs for channel {id}", channelId);
+
+ string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ var reader = new XmlTvReader(path, GetLanguage(info));
+
+ return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken)
+ .Select(p => GetProgramInfo(p, info));
+ }
+
+ private ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info)
+ {
+ string episodeTitle = program.Episode?.Title;
+
+ var programInfo = new ProgramInfo
+ {
+ ChannelId = program.ChannelId,
+ EndDate = program.EndDate.UtcDateTime,
+ EpisodeNumber = program.Episode?.Episode,
+ EpisodeTitle = episodeTitle,
+ Genres = program.Categories,
+ StartDate = program.StartDate.UtcDateTime,
+ Name = program.Title,
+ Overview = program.Description,
+ ProductionYear = program.CopyrightDate?.Year,
+ SeasonNumber = program.Episode?.Series,
+ IsSeries = program.Episode != null,
+ IsRepeat = program.IsPreviouslyShown && !program.IsNew,
+ IsPremiere = program.Premiere != null,
+ IsKids = program.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
+ IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
+ IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
+ IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
+ ImageUrl = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null,
+ HasImage = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source),
+ OfficialRating = program.Rating != null && !String.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null,
+ CommunityRating = program.StarRating,
+ SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N")
+ };
+
+ if (string.IsNullOrWhiteSpace(program.ProgramId))
+ {
+ string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/;
+
+ if (programInfo.SeasonNumber.HasValue)
+ {
+ uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture);
+ }
+ if (programInfo.EpisodeNumber.HasValue)
+ {
+ uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
+ }
+
+ programInfo.ShowId = uniqueString.GetMD5().ToString("N");
+
+ // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
+ if (programInfo.IsSeries
+ && !programInfo.IsRepeat
+ && (programInfo.EpisodeNumber ?? 0) == 0)
+ {
+ programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+ else
+ {
+ programInfo.ShowId = program.ProgramId;
+ }
+
+ // Construct an id from the channel and start date
+ programInfo.Id = String.Format("{0}_{1:O}", program.ChannelId, program.StartDate);
+
+ if (programInfo.IsMovie)
+ {
+ programInfo.IsSeries = false;
+ programInfo.EpisodeNumber = null;
+ programInfo.EpisodeTitle = null;
+ }
+
+ return programInfo;
+ }
+
+ public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
+ {
+ // Assume all urls are valid. check files for existence
+ if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path))
+ {
+ throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
+ {
+ // In theory this should never be called because there is always only one lineup
+ string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ var reader = new XmlTvReader(path, GetLanguage(info));
+ IEnumerable<XmlTvChannel> results = reader.GetChannels();
+
+ // Should this method be async?
+ return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
+ }
+
+ public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
+ {
+ // In theory this should never be called because there is always only one lineup
+ string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
+ _logger.LogDebug("Opening XmlTvReader for {path}", path);
+ var reader = new XmlTvReader(path, GetLanguage(info));
+ IEnumerable<XmlTvChannel> results = reader.GetChannels();
+
+ // Should this method be async?
+ return results.Select(c => new ChannelInfo
+ {
+ Id = c.Id,
+ Name = c.DisplayName,
+ ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null,
+ Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number
+
+ }).ToList();
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
index b0ffd057d..6fe578715 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
@@ -170,6 +170,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
@@ -185,6 +186,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
}
@@ -212,6 +214,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
@@ -230,6 +233,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
}
@@ -260,6 +264,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
@@ -275,6 +280,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
}
@@ -333,6 +339,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
+ _logger.LogError(ex, "Error");
}
}
}
@@ -376,7 +383,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting image info for {0}", ex, info.Name);
+ _logger.LogError(ex, "Error getting image info for {name}", info.Name);
}
return null;
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
index 2e9679678..b597a935a 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
@@ -1,5 +1,4 @@
-using MediaBrowser.Common;
-using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
@@ -14,22 +13,18 @@ using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Serialization;
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Common.Events;
using MediaBrowser.Common.Security;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
@@ -136,9 +131,7 @@ namespace Emby.Server.Implementations.LiveTv
{
service.DataSourceChanged += service_DataSourceChanged;
- var embyTv = service as EmbyTV.EmbyTV;
-
- if (embyTv != null)
+ if (service is EmbyTV.EmbyTV embyTv)
{
embyTv.TimerCreated += EmbyTv_TimerCreated;
embyTv.TimerCancelled += EmbyTv_TimerCancelled;
@@ -150,13 +143,13 @@ namespace Emby.Server.Implementations.LiveTv
{
var timerId = e.Argument;
- EventHelper.FireEventIfNotNull(TimerCancelled, this, new GenericEventArgs<TimerEventInfo>
+ TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = timerId
}
- }, _logger);
+ });
}
private void EmbyTv_TimerCreated(object sender, GenericEventArgs<TimerInfo> e)
@@ -164,14 +157,14 @@ namespace Emby.Server.Implementations.LiveTv
var timer = e.Argument;
var service = sender as ILiveTvService;
- EventHelper.FireEventIfNotNull(TimerCreated, this, new GenericEventArgs<TimerEventInfo>
+ TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId),
Id = timer.Id
}
- }, _logger);
+ });
}
public ITunerHost[] TunerHosts
@@ -255,18 +248,15 @@ namespace Emby.Server.Implementations.LiveTv
mediaSourceId = null;
}
- MediaSourceInfo info;
- bool isVideo;
- ILiveTvService service;
- ILiveStream liveStream;
-
var channel = (LiveTvChannel)_libraryManager.GetItemById(id);
- isVideo = channel.ChannelType == ChannelType.TV;
- service = GetService(channel);
- _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
- var supportsManagedStream = service as ISupportsDirectStreamProvider;
- if (supportsManagedStream != null)
+ bool isVideo = channel.ChannelType == ChannelType.TV;
+ ILiveTvService service = GetService(channel);
+ _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
+
+ MediaSourceInfo info;
+ ILiveStream liveStream;
+ if (service is ISupportsDirectStreamProvider supportsManagedStream)
{
liveStream = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(channel.ExternalId, mediaSourceId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
info = liveStream.MediaSource;
@@ -282,7 +272,7 @@ namespace Emby.Server.Implementations.LiveTv
var startTime = DateTime.UtcNow;
await liveStream.Open(cancellationToken).ConfigureAwait(false);
var endTime = DateTime.UtcNow;
- _logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
+ _logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
}
info.RequiresClosing = true;
@@ -307,14 +297,12 @@ namespace Emby.Server.Implementations.LiveTv
throw new NotImplementedException();
}
- var list = sources.ToList();
-
- foreach (var source in list)
+ foreach (var source in sources)
{
Normalize(source, service, baseItem.ChannelType == ChannelType.TV);
}
- return list;
+ return sources;
}
private ILiveTvService GetService(LiveTvChannel item)
@@ -546,13 +534,11 @@ namespace Emby.Server.Implementations.LiveTv
{
var id = _tvDtoService.GetInternalProgramId(info.Id);
- LiveTvProgram item = null;
- allExistingPrograms.TryGetValue(id, out item);
-
var isNew = false;
var forceUpdate = false;
- if (item == null)
+ LiveTvProgram item;
+ if (!allExistingPrograms.TryGetValue(id, out item))
{
isNew = true;
item = new LiveTvProgram
@@ -787,11 +773,9 @@ namespace Emby.Server.Implementations.LiveTv
var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
- var list = new List<Tuple<BaseItemDto, string, string>>();
-
- var externalSeriesId = program.ExternalSeriesId;
-
- list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, externalSeriesId));
+ var list = new List<Tuple<BaseItemDto, string, string>>() {
+ new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId)
+ };
await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
@@ -932,13 +916,11 @@ namespace Emby.Server.Implementations.LiveTv
programs = programs.Take(query.Limit.Value);
}
- var result = new QueryResult<BaseItem>
- {
- Items = programs.ToArray(),
- TotalRecordCount = totalCount
- };
-
- return result;
+ return new QueryResult<BaseItem>
+ {
+ Items = programs.ToArray(),
+ TotalRecordCount = totalCount
+ };
}
public QueryResult<BaseItemDto> GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken)
@@ -952,17 +934,11 @@ namespace Emby.Server.Implementations.LiveTv
var internalResult = GetRecommendedProgramsInternal(query, options, cancellationToken);
- var user = query.User;
-
- var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user);
-
- var result = new QueryResult<BaseItemDto>
- {
- Items = returnArray,
- TotalRecordCount = internalResult.TotalRecordCount
- };
-
- return result;
+ return new QueryResult<BaseItemDto>
+ {
+ Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User),
+ TotalRecordCount = internalResult.TotalRecordCount
+ };
}
private int GetRecommendationScore(LiveTvProgram program, User user, bool factorChannelWatchCount)
@@ -981,28 +957,26 @@ namespace Emby.Server.Implementations.LiveTv
var channel = _libraryManager.GetItemById(program.ChannelId);
- if (channel != null)
+ if (channel == null)
{
- var channelUserdata = _userDataManager.GetUserData(user, channel);
+ return score;
+ }
- if (channelUserdata.Likes ?? false)
- {
- score += 2;
- }
- else if (!(channelUserdata.Likes ?? true))
- {
- score -= 2;
- }
+ var channelUserdata = _userDataManager.GetUserData(user, channel);
- if (channelUserdata.IsFavorite)
- {
- score += 3;
- }
+ if (channelUserdata.Likes.HasValue)
+ {
+ score += channelUserdata.Likes.Value ? 2 : -2;
+ }
- if (factorChannelWatchCount)
- {
- score += channelUserdata.PlayCount;
- }
+ if (channelUserdata.IsFavorite)
+ {
+ score += 3;
+ }
+
+ if (factorChannelWatchCount)
+ {
+ score += channelUserdata.PlayCount;
}
return score;
@@ -1093,7 +1067,7 @@ namespace Emby.Server.Implementations.LiveTv
{
cancellationToken.ThrowIfCancellationRequested();
- _logger.Debug("Refreshing guide from {0}", service.Name);
+ _logger.LogDebug("Refreshing guide from {name}", service.Name);
try
{
@@ -1112,7 +1086,7 @@ namespace Emby.Server.Implementations.LiveTv
catch (Exception ex)
{
cleanDatabase = false;
- _logger.ErrorException("Error refreshing channels for service", ex);
+ _logger.LogError(ex, "Error refreshing channels for service");
}
numComplete++;
@@ -1157,7 +1131,6 @@ namespace Emby.Server.Implementations.LiveTv
var numComplete = 0;
var parentFolder = GetInternalLiveTvFolder(cancellationToken);
- var parentFolderId = parentFolder.Id;
foreach (var channelInfo in allChannelsList)
{
@@ -1175,7 +1148,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
+ _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name);
}
numComplete++;
@@ -1193,7 +1166,7 @@ namespace Emby.Server.Implementations.LiveTv
var guideDays = GetGuideDays();
- _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
+ _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays);
cancellationToken.ThrowIfCancellationRequested();
@@ -1243,33 +1216,14 @@ namespace Emby.Server.Implementations.LiveTv
programs.Add(programItem.Id);
- if (program.IsMovie)
- {
- isMovie = true;
- }
-
- if (program.IsSeries)
- {
- iSSeries = true;
- }
-
- if (program.IsSports)
- {
- isSports = true;
- }
-
- if (program.IsNews)
- {
- isNews = true;
- }
-
- if (program.IsKids)
- {
- isKids = true;
- }
+ isMovie |= program.IsMovie;
+ iSSeries |= program.IsSeries;
+ isSports |= program.IsSports;
+ isNews |= program.IsNews;
+ isKids |= program.IsKids;
}
- _logger.Debug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
+ _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
if (newPrograms.Count > 0)
{
@@ -1292,7 +1246,7 @@ namespace Emby.Server.Implementations.LiveTv
}
//currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken);
- await currentChannel.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
+ await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ForceSave = true
@@ -1304,12 +1258,11 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
+ _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name);
}
numComplete++;
- double percent = numComplete;
- percent /= allChannelsList.Count;
+ double percent = numComplete / allChannelsList.Count;
progress.Report(85 * percent + 15);
}
@@ -1324,7 +1277,6 @@ namespace Emby.Server.Implementations.LiveTv
{
IncludeItemTypes = validTypes,
DtoOptions = new DtoOptions(false)
-
});
var numComplete = 0;
@@ -1355,8 +1307,7 @@ namespace Emby.Server.Implementations.LiveTv
}
numComplete++;
- double percent = numComplete;
- percent /= list.Count;
+ double percent = numComplete / list.Count;
progress.Report(100 * percent);
}
@@ -1418,28 +1369,22 @@ namespace Emby.Server.Implementations.LiveTv
excludeItemTypes.Add(typeof(Episode).Name);
}
}
- if (query.IsSports.HasValue)
+ if (query.IsSports ?? false)
{
- if (query.IsSports.Value)
- {
- genres.Add("Sports");
- }
+ genres.Add("Sports");
}
- if (query.IsKids.HasValue)
+ if (query.IsKids ?? false)
{
- if (query.IsKids.Value)
- {
- genres.Add("Kids");
- genres.Add("Children");
- genres.Add("Family");
- }
+ genres.Add("Kids");
+ genres.Add("Children");
+ genres.Add("Family");
}
var limit = query.Limit;
- if ((query.IsInProgress ?? false))
+ if (query.IsInProgress ?? false)
{
- limit = (query.Limit ?? 10) * 2;
+ // limit = (query.Limit ?? 10) * 2;
limit = null;
//var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray();
@@ -1471,7 +1416,7 @@ namespace Emby.Server.Implementations.LiveTv
DtoOptions = dtoOptions
});
- if ((query.IsInProgress ?? false))
+ if (query.IsInProgress ?? false)
{
result.Items = result
.Items
@@ -1498,60 +1443,33 @@ namespace Emby.Server.Implementations.LiveTv
dto.StartDate = program.StartDate;
dto.EpisodeTitle = program.EpisodeTitle;
-
- if (program.IsRepeat)
- {
- dto.IsRepeat = program.IsRepeat;
- }
- if (program.IsMovie)
- {
- dto.IsMovie = program.IsMovie;
- }
- if (program.IsSeries)
- {
- dto.IsSeries = program.IsSeries;
- }
- if (program.IsSports)
- {
- dto.IsSports = program.IsSports;
- }
- if (program.IsLive)
- {
- dto.IsLive = program.IsLive;
- }
- if (program.IsNews)
- {
- dto.IsNews = program.IsNews;
- }
- if (program.IsKids)
- {
- dto.IsKids = program.IsKids;
- }
- if (program.IsPremiere)
- {
- dto.IsPremiere = program.IsPremiere;
- }
+ dto.IsRepeat |= program.IsRepeat;
+ dto.IsMovie |= program.IsMovie;
+ dto.IsSeries |= program.IsSeries;
+ dto.IsSports |= program.IsSports;
+ dto.IsLive |= program.IsLive;
+ dto.IsNews |= program.IsNews;
+ dto.IsKids |= program.IsKids;
+ dto.IsPremiere |= program.IsPremiere;
if (hasChannelInfo || hasChannelImage)
{
- var channel = _libraryManager.GetItemById(program.ChannelId) as LiveTvChannel;
+ var channel = _libraryManager.GetItemById(program.ChannelId);
- if (channel != null)
+ if (channel is LiveTvChannel liveChannel)
{
- dto.ChannelName = channel.Name;
- dto.MediaType = channel.MediaType;
- dto.ChannelNumber = channel.Number;
+ dto.ChannelName = liveChannel.Name;
+ dto.MediaType = liveChannel.MediaType;
+ dto.ChannelNumber = liveChannel.Number;
- if (hasChannelImage && channel.HasImage(ImageType.Primary))
+ if (hasChannelImage && liveChannel.HasImage(ImageType.Primary))
{
- dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
+ dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(liveChannel);
}
}
}
- var externalSeriesId = program.ExternalSeriesId;
-
- programTuples.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, externalSeriesId));
+ programTuples.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId));
}
return AddRecordingInfo(programTuples, CancellationToken.None);
@@ -1649,7 +1567,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting recordings", ex);
+ _logger.LogError(ex, "Error getting recordings");
return new List<Tuple<TimerInfo, ILiveTvService>>();
}
});
@@ -1725,7 +1643,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting recordings", ex);
+ _logger.LogError(ex, "Error getting recordings");
return new List<Tuple<TimerInfo, ILiveTvService>>();
}
});
@@ -1815,13 +1733,13 @@ namespace Emby.Server.Implementations.LiveTv
if (!(service is EmbyTV.EmbyTV))
{
- EventHelper.FireEventIfNotNull(TimerCancelled, this, new GenericEventArgs<TimerEventInfo>
+ TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = id
}
- }, _logger);
+ });
}
}
@@ -1838,13 +1756,13 @@ namespace Emby.Server.Implementations.LiveTv
await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
- EventHelper.FireEventIfNotNull(SeriesTimerCancelled, this, new GenericEventArgs<TimerEventInfo>
+ SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
Id = id
}
- }, _logger);
+ });
}
public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
@@ -1880,7 +1798,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting recordings", ex);
+ _logger.LogError(ex, "Error getting recordings");
return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
}
});
@@ -1926,7 +1844,7 @@ namespace Emby.Server.Implementations.LiveTv
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting recordings", ex);
+ _logger.LogError(ex, "Error getting recordings");
return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
}
});
@@ -2041,19 +1959,13 @@ namespace Emby.Server.Implementations.LiveTv
private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
{
- var service = program != null ?
- GetService(program) :
- null;
-
- if (service == null)
- {
- service = _services.First();
- }
-
+ ILiveTvService service = null;
ProgramInfo programInfo = null;
- if (program != null)
+ if(program != null)
{
+ service = GetService(program);
+
var channel = _libraryManager.GetItemById(program.ChannelId);
programInfo = new ProgramInfo
@@ -2081,6 +1993,11 @@ namespace Emby.Server.Implementations.LiveTv
Name = program.Name,
OfficialRating = program.OfficialRating
};
+ }
+
+ if (service == null)
+ {
+ service = _services.First();
}
var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
@@ -2151,8 +2068,7 @@ namespace Emby.Server.Implementations.LiveTv
info.Priority = defaultValues.Priority;
string newTimerId = null;
- var supportsNewTimerIds = service as ISupportsNewTimerIds;
- if (supportsNewTimerIds != null)
+ if (service is ISupportsNewTimerIds supportsNewTimerIds)
{
newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false);
newTimerId = _tvDtoService.GetInternalTimerId(newTimerId);
@@ -2162,18 +2078,18 @@ namespace Emby.Server.Implementations.LiveTv
await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
}
- _logger.Info("New recording scheduled");
+ _logger.LogInformation("New recording scheduled");
if (!(service is EmbyTV.EmbyTV))
{
- EventHelper.FireEventIfNotNull(TimerCreated, this, new GenericEventArgs<TimerEventInfo>
+ TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
Id = newTimerId
}
- }, _logger);
+ });
}
}
@@ -2183,7 +2099,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!registration.IsValid)
{
- _logger.Info("Creating series recordings requires an active Emby Premiere subscription.");
+ _logger.LogInformation("Creating series recordings requires an active Emby Premiere subscription.");
return;
}
@@ -2196,8 +2112,7 @@ namespace Emby.Server.Implementations.LiveTv
info.Priority = defaultValues.Priority;
string newTimerId = null;
- var supportsNewTimerIds = service as ISupportsNewTimerIds;
- if (supportsNewTimerIds != null)
+ if (service is ISupportsNewTimerIds supportsNewTimerIds)
{
newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N");
@@ -2207,14 +2122,14 @@ namespace Emby.Server.Implementations.LiveTv
await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
}
- EventHelper.FireEventIfNotNull(SeriesTimerCreated, this, new GenericEventArgs<TimerEventInfo>
+ SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
{
Argument = new TimerEventInfo
{
ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
Id = newTimerId
}
- }, _logger);
+ });
}
public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
@@ -2358,8 +2273,7 @@ namespace Emby.Server.Implementations.LiveTv
throw new ResourceNotFoundException();
}
- var configurable = provider as IConfigurableTunerHost;
- if (configurable != null)
+ if (provider is IConfigurableTunerHost configurable)
{
await configurable.Validate(info).ConfigureAwait(false);
}
@@ -2392,21 +2306,25 @@ namespace Emby.Server.Implementations.LiveTv
public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
{
+ // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider
+ // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider
info = _jsonSerializer.DeserializeFromString<ListingsProviderInfo>(_jsonSerializer.SerializeToString(info));
- var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
+ IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
if (provider == null)
{
- throw new ResourceNotFoundException();
+ throw new ResourceNotFoundException(
+ string.Format("Couldn't find provider of type: '{0}'", info.Type)
+ );
}
await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
- var config = GetConfiguration();
+ LiveTvOptions config = GetConfiguration();
- var list = config.ListingProviders.ToList();
- var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
+ List<ListingsProviderInfo> list = config.ListingProviders.ToList();
+ int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
index 26a84a275..d13f08b1b 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -29,14 +29,14 @@ namespace Emby.Server.Implementations.LiveTv
private readonly IServerApplicationHost _appHost;
private IApplicationPaths _appPaths;
- public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost)
+ public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost)
{
_liveTvManager = liveTvManager;
_jsonSerializer = jsonSerializer;
_mediaSourceManager = mediaSourceManager;
_mediaEncoder = mediaEncoder;
_appHost = appHost;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
_appPaths = appPaths;
}
@@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.LiveTv
}
}
- _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list));
+ _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list));
return list;
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
index ca5e51971..ef2010ba6 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
var list = result.ToList();
- //Logger.Info("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
+ //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
if (!string.IsNullOrEmpty(key) && list.Count > 0)
{
@@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting channel list", ex);
+ Logger.LogError(ex, "Error getting channel list");
if (enableCache)
{
@@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.Error("Error getting channels", ex);
+ Logger.LogError(ex, "Error getting channels");
}
}
}
@@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.Error("Error getting channels", ex);
+ Logger.LogError(ex, "Error getting channels");
}
}
@@ -216,12 +216,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
var startTime = DateTime.UtcNow;
await liveStream.Open(cancellationToken).ConfigureAwait(false);
var endTime = DateTime.UtcNow;
- Logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
+ Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
return liveStream;
}
catch (Exception ex)
{
- Logger.Error("Error opening tuner", ex);
+ Logger.LogError(ex, "Error opening tuner");
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
index e873eb8e9..be090df0c 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -303,7 +303,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting tuner info", ex);
+ Logger.LogError(ex, "Error getting tuner info");
}
}
@@ -581,7 +581,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
var profile = streamId.Split('_')[0];
- Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile);
+ Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile);
var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id);
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
index 2bc5a0ed3..0e84622bd 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
@@ -6,7 +6,7 @@ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Controller.LiveTv;
using System.Net;
@@ -244,7 +244,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
private async Task ReleaseLockkey(ISocket tcpClient, uint lockKeyValue)
{
- _logger.Info("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue);
+ _logger.LogInformation("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue);
var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort);
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
index 33103979e..c781bccbb 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.System;
using MediaBrowser.Model.LiveTv;
@@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath));
- Logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host);
+ Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);
var remoteAddress = IPAddress.Parse(uri.Host);
var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host);
@@ -69,9 +69,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address;
tcpSocket.Close();
}
- catch (Exception)
+ catch (Exception ex)
{
- Logger.Error("Unable to determine local ip address for Legacy HDHomerun stream.");
+ Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream.");
return;
}
}
@@ -87,21 +87,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
catch (Exception ex)
{
using (udpClient)
+ using (hdHomerunManager)
{
- using (hdHomerunManager)
+ if (!(ex is OperationCanceledException))
{
- if (!(ex is OperationCanceledException))
- {
- Logger.ErrorException("Error opening live stream:", ex);
- }
- throw;
+ Logger.LogError(ex, "Error opening live stream:");
}
+ throw;
}
}
var taskCompletionSource = new TaskCompletionSource<bool>();
- StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
+ await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
//OpenedMediaSource.Protocol = MediaProtocol.File;
//OpenedMediaSource.Path = tempFile;
@@ -122,26 +120,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return Task.Run(async () =>
{
using (udpClient)
+ using (hdHomerunManager)
{
- using (hdHomerunManager)
+ try
{
- try
- {
- await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException ex)
- {
- Logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
- openTaskCompletionSource.TrySetException(ex);
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error opening live stream:", ex);
- openTaskCompletionSource.TrySetException(ex);
- }
-
- EnableStreamSharing = false;
+ await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
}
+ catch (OperationCanceledException ex)
+ {
+ Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
+ openTaskCompletionSource.TrySetException(ex);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error opening live stream:");
+ openTaskCompletionSource.TrySetException(ex);
+ }
+
+ EnableStreamSharing = false;
}
await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
@@ -166,30 +162,28 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var resolved = false;
using (var source = _socketFactory.CreateNetworkStream(udpClient, false))
+ using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
{
- using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
- {
- var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token;
+ var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token;
- while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- currentCancellationToken = cancellationToken;
+ currentCancellationToken = cancellationToken;
- read -= RtpHeaderBytes;
+ read -= RtpHeaderBytes;
- if (read > 0)
- {
- fileStream.Write(buffer, RtpHeaderBytes, read);
- }
+ if (read > 0)
+ {
+ fileStream.Write(buffer, RtpHeaderBytes, read);
+ }
- if (!resolved)
- {
- resolved = true;
- DateOpened = DateTime.UtcNow;
- Resolve(openTaskCompletionSource);
- }
+ if (!resolved)
+ {
+ resolved = true;
+ DateOpened = DateTime.UtcNow;
+ Resolve(openTaskCompletionSource);
}
}
}
@@ -346,4 +340,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
index 7e0ac4131..4a2b4ebb2 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
using MediaBrowser.Model.LiveTv;
using System.Linq;
@@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
EnableStreamSharing = false;
- Logger.Info("Closing " + GetType().Name);
+ Logger.LogInformation("Closing " + GetType().Name);
LiveStreamCancellationTokenSource.Cancel();
@@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.ErrorException("Error closing live stream", ex);
+ Logger.LogError(ex, "Error closing live stream");
}
}
@@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
if (retryCount == 0)
{
- Logger.Info("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
+ Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
}
var failedFiles = new List<string>();
@@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- //Logger.ErrorException("Error deleting file {0}", ex, path);
+ Logger.LogError(ex, "Error deleting file {path}", path);
failedFiles.Add(path);
}
}
@@ -181,14 +181,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
isLastFile = nextFileInfo.Item2;
}
- Logger.Info("Live Stream ended.");
+ Logger.LogInformation("Live Stream ended.");
}
private Tuple<string, bool> GetNextFile(string currentFile)
{
var files = GetStreamFilePaths();
- //Logger.Info("Live stream files: {0}", string.Join(", ", files.ToArray()));
+ //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
if (string.IsNullOrEmpty(currentFile))
{
@@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
{
- //Logger.Info("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
+ //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
{
@@ -227,7 +227,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private void TrySeek(FileStream stream, long offset)
{
- //Logger.Info("TrySeek live stream");
+ //logger.LogInformation("TrySeek live stream");
try
{
stream.Seek(offset, SeekOrigin.End);
@@ -242,7 +242,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.ErrorException("Error seeking stream", ex);
+ Logger.LogError(ex, "Error seeking stream");
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
index a1bff2b5b..a54bd1613 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
@@ -205,4 +205,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return Task.FromResult(new List<TunerHostInfo>());
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
index ca744b615..208225c1e 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs
@@ -12,7 +12,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
@@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase))
{
extInf = line.Substring(ExtInfPrefix.Length).Trim();
- _logger.Info("Found m3u channel: {0}", extInf);
+ _logger.LogInformation("Found m3u channel: {0}", extInf);
}
else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase))
{
@@ -335,4 +335,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return dict;
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
index 572edb167..9b10daba0 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs
@@ -9,7 +9,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.System;
using System.Globalization;
@@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath));
var typeName = GetType().Name;
- Logger.Info("Opening " + typeName + " Live stream from {0}", url);
+ Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url);
var httpRequestOptions = new HttpRequestOptions
{
@@ -125,17 +125,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
try
{
+ Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
using (response)
+ using (var stream = response.Content)
+ using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
{
- using (var stream = response.Content)
- {
- Logger.Info("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
-
- using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
- {
- await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false);
- }
- }
+ await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -143,7 +138,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
}
catch (Exception ex)
{
- Logger.ErrorException("Error copying live stream.", ex);
+ Logger.LogError(ex, "Error copying live stream.");
}
EnableStreamSharing = false;
await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs
index 71a4ca824..c6de9d957 100644
--- a/Emby.Server.Implementations/Localization/LocalizationManager.cs
+++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs
@@ -10,7 +10,7 @@ using System.Globalization;
using System.IO;
using System.Linq;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Reflection;
namespace Emby.Server.Implementations.Localization
@@ -82,7 +82,7 @@ namespace Emby.Server.Implementations.Localization
using (var stream = _assemblyInfo.GetManifestResourceStream(type, resource))
{
var target = Path.Combine(localizationPath, filename);
- _logger.Info("Extracting ratings to {0}", target);
+ _logger.LogInformation("Extracting ratings to {0}", target);
using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
{
diff --git a/Emby.Server.Implementations/Logging/ConsoleLogger.cs b/Emby.Server.Implementations/Logging/ConsoleLogger.cs
deleted file mode 100644
index 51199f08a..000000000
--- a/Emby.Server.Implementations/Logging/ConsoleLogger.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System;
-using MediaBrowser.Model.Logging;
-
-namespace Emby.Server.Implementations.Logging
-{
- public class ConsoleLogger : IConsoleLogger
- {
- public void WriteLine(string message)
- {
- Console.WriteLine(message);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Logging/SimpleLogManager.cs b/Emby.Server.Implementations/Logging/SimpleLogManager.cs
deleted file mode 100644
index 390814c34..000000000
--- a/Emby.Server.Implementations/Logging/SimpleLogManager.cs
+++ /dev/null
@@ -1,360 +0,0 @@
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Logging;
-
-namespace Emby.Server.Implementations.Logging
-{
- public class SimpleLogManager : ILogManager, IDisposable
- {
- public LogSeverity LogSeverity { get; set; }
- public string ExceptionMessagePrefix { get; set; }
- private FileLogger _fileLogger;
-
- private readonly string LogDirectory;
- private readonly string LogFilePrefix;
- public string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
-
- public SimpleLogManager(string logDirectory, string logFileNamePrefix)
- {
- LogDirectory = logDirectory;
- LogFilePrefix = logFileNamePrefix;
- }
-
- public ILogger GetLogger(string name)
- {
- return new NamedLogger(name, this);
- }
-
- public async Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken)
- {
- LogSeverity = severity;
-
- var logger = _fileLogger;
- if (logger != null)
- {
- logger.Dispose();
- await TryMoveToArchive(logger.Path, cancellationToken).ConfigureAwait(false);
- }
-
- var newPath = Path.Combine(LogDirectory, LogFilePrefix + ".txt");
-
- if (File.Exists(newPath))
- {
- newPath = await TryMoveToArchive(newPath, cancellationToken).ConfigureAwait(false);
- }
-
- _fileLogger = new FileLogger(newPath);
-
- if (LoggerLoaded != null)
- {
- try
- {
- LoggerLoaded(this, EventArgs.Empty);
- }
- catch (Exception ex)
- {
- GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex);
- }
- }
- }
-
- private async Task<string> TryMoveToArchive(string file, CancellationToken cancellationToken, int retryCount = 0)
- {
- var archivePath = GetArchiveFilePath();
-
- try
- {
- File.Move(file, archivePath);
-
- return file;
- }
- catch (FileNotFoundException)
- {
- return file;
- }
- catch (DirectoryNotFoundException)
- {
- return file;
- }
- catch
- {
- if (retryCount >= 50)
- {
- return GetArchiveFilePath();
- }
-
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
-
- return await TryMoveToArchive(file, cancellationToken, retryCount + 1).ConfigureAwait(false);
- }
- }
-
- private string GetArchiveFilePath()
- {
- return Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Floor(DateTime.Now.Ticks / 10000000) + ".txt");
- }
-
- public event EventHandler LoggerLoaded;
-
- public void Flush()
- {
- var logger = _fileLogger;
- if (logger != null)
- {
- logger.Flush();
- }
- }
-
- private bool _console = true;
- public void AddConsoleOutput()
- {
- _console = true;
- }
-
- public void RemoveConsoleOutput()
- {
- _console = false;
- }
-
- public void Log(string message)
- {
- if (_console)
- {
- Console.WriteLine(message);
- }
-
- var logger = _fileLogger;
- if (logger != null)
- {
- message = DateTime.Now.ToString(DateTimeFormat) + " " + message;
-
- logger.Log(message);
- }
- }
-
- public void Dispose()
- {
- var logger = _fileLogger;
- if (logger != null)
- {
- logger.Dispose();
-
- var task = TryMoveToArchive(logger.Path, CancellationToken.None);
- Task.WaitAll(task);
- }
-
- _fileLogger = null;
- }
- }
-
- public class FileLogger : IDisposable
- {
- private readonly FileStream _fileStream;
-
- private bool _disposed;
- private readonly CancellationTokenSource _cancellationTokenSource;
- private readonly BlockingCollection<string> _queue = new BlockingCollection<string>();
-
- public string Path { get; set; }
-
- public FileLogger(string path)
- {
- Path = path;
-
- Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
-
- _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 32768);
- _cancellationTokenSource = new CancellationTokenSource();
-
- Task.Factory.StartNew(LogInternal, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
- }
-
- private void LogInternal()
- {
- while (!_cancellationTokenSource.IsCancellationRequested && !_disposed)
- {
- try
- {
- foreach (var message in _queue.GetConsumingEnumerable())
- {
- var bytes = Encoding.UTF8.GetBytes(message + Environment.NewLine);
- if (_disposed)
- {
- return;
- }
-
- _fileStream.Write(bytes, 0, bytes.Length);
- if (_disposed)
- {
- return;
- }
-
- _fileStream.Flush(true);
- }
- }
- catch
- {
-
- }
- }
- }
-
- public void Log(string message)
- {
- if (_disposed)
- {
- return;
- }
-
- _queue.Add(message);
- }
-
- public void Flush()
- {
- if (_disposed)
- {
- return;
- }
-
- _fileStream.Flush(true);
- }
-
- public void Dispose()
- {
- if (_disposed)
- {
- return;
- }
-
- _disposed = true;
- _cancellationTokenSource.Cancel();
-
- var stream = _fileStream;
- if (stream != null)
- {
- using (stream)
- {
- stream.Flush(true);
- }
- }
- }
- }
-
- public class NamedLogger : ILogger
- {
- public string Name { get; private set; }
- private readonly SimpleLogManager _logManager;
-
- public NamedLogger(string name, SimpleLogManager logManager)
- {
- Name = name;
- _logManager = logManager;
- }
-
- public void Info(string message, params object[] paramList)
- {
- Log(LogSeverity.Info, message, paramList);
- }
-
- public void Error(string message, params object[] paramList)
- {
- Log(LogSeverity.Error, message, paramList);
- }
-
- public void Warn(string message, params object[] paramList)
- {
- Log(LogSeverity.Warn, message, paramList);
- }
-
- public void Debug(string message, params object[] paramList)
- {
- if (_logManager.LogSeverity == LogSeverity.Info)
- {
- return;
- }
- Log(LogSeverity.Debug, message, paramList);
- }
-
- public void Fatal(string message, params object[] paramList)
- {
- Log(LogSeverity.Fatal, message, paramList);
- }
-
- public void FatalException(string message, Exception exception, params object[] paramList)
- {
- ErrorException(message, exception, paramList);
- }
-
- public void ErrorException(string message, Exception exception, params object[] paramList)
- {
- LogException(LogSeverity.Error, message, exception, paramList);
- }
-
- private void LogException(LogSeverity level, string message, Exception exception, params object[] paramList)
- {
- message = FormatMessage(message, paramList).Replace(Environment.NewLine, ". ");
-
- var messageText = LogHelper.GetLogMessage(exception);
-
- var prefix = _logManager.ExceptionMessagePrefix;
-
- if (!string.IsNullOrWhiteSpace(prefix))
- {
- messageText.Insert(0, prefix);
- }
-
- LogMultiline(message, level, messageText);
- }
-
- private static string FormatMessage(string message, params object[] paramList)
- {
- if (paramList != null)
- {
- for (var i = 0; i < paramList.Length; i++)
- {
- var obj = paramList[i];
-
- message = message.Replace("{" + i + "}", (obj == null ? "null" : obj.ToString()));
- }
- }
-
- return message;
- }
-
- public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent)
- {
- if (severity == LogSeverity.Debug && _logManager.LogSeverity == LogSeverity.Info)
- {
- return;
- }
-
- additionalContent.Insert(0, message + Environment.NewLine);
-
- const char tabChar = '\t';
-
- var text = additionalContent.ToString()
- .Replace(Environment.NewLine, Environment.NewLine + tabChar)
- .TrimEnd(tabChar);
-
- if (text.EndsWith(Environment.NewLine))
- {
- text = text.Substring(0, text.LastIndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase));
- }
-
- Log(severity, text);
- }
-
- public void Log(LogSeverity severity, string message, params object[] paramList)
- {
- message = severity + " " + Name + ": " + FormatMessage(message, paramList);
-
- _logManager.Log(message);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs b/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs
deleted file mode 100644
index 7104935e1..000000000
--- a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Logging;
-using System;
-using System.IO;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Server.Implementations.Logging
-{
- public class UnhandledExceptionWriter
- {
- private readonly IApplicationPaths _appPaths;
- private readonly ILogger _logger;
- private readonly ILogManager _logManager;
- private readonly IFileSystem _fileSystem;
- private readonly IConsoleLogger _console;
-
- public UnhandledExceptionWriter(IApplicationPaths appPaths, ILogger logger, ILogManager logManager, IFileSystem fileSystem, IConsoleLogger console)
- {
- _appPaths = appPaths;
- _logger = logger;
- _logManager = logManager;
- _fileSystem = fileSystem;
- _console = console;
- }
-
- public void Log(Exception ex)
- {
- _logger.ErrorException("UnhandledException", ex);
- _logManager.Flush();
-
- var path = Path.Combine(_appPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt");
- _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
-
- var builder = LogHelper.GetLogMessage(ex);
-
- // Write to console just in case file logging fails
- _console.WriteLine("UnhandledException");
-
- var logMessage = builder.ToString();
- _console.WriteLine(logMessage);
-
- _fileSystem.WriteAllText(path, logMessage);
- }
- }
-}
diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
index c6033b4f4..792ffb3c4 100644
--- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
+++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
@@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.MediaEncoder
{
if (chapter.StartPositionTicks >= runtimeTicks)
{
- _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
+ _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
break;
}
@@ -166,7 +166,7 @@ namespace Emby.Server.Implementations.MediaEncoder
}
catch (Exception ex)
{
- _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path));
+ _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path));
success = false;
break;
}
@@ -226,7 +226,7 @@ namespace Emby.Server.Implementations.MediaEncoder
foreach (var image in deadImages)
{
- _logger.Debug("Deleting dead chapter image {0}", image);
+ _logger.LogDebug("Deleting dead chapter image {path}", image);
try
{
@@ -234,7 +234,7 @@ namespace Emby.Server.Implementations.MediaEncoder
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting {0}.", ex, image);
+ _logger.LogError(ex, "Error deleting {path}.", image);
}
}
}
diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs
index 9726ef097..3f93e767f 100644
--- a/Emby.Server.Implementations/Net/SocketFactory.cs
+++ b/Emby.Server.Implementations/Net/SocketFactory.cs
@@ -3,7 +3,7 @@ using System.IO;
using System.Net;
using System.Net.Sockets;
using Emby.Server.Implementations.Networking;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
namespace Emby.Server.Implementations.Net
diff --git a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs b/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs
index 6d7785b90..8d0fb7997 100644
--- a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs
+++ b/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs
@@ -189,7 +189,7 @@ namespace System.Net
internal
#endif
- IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr)
+ IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr)
{
int maxCidr = family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
@@ -1164,18 +1164,6 @@ namespace System.Net
}
- [Obsolete("static Contains is deprecated, please use instance Contains.")]
- public static bool Contains(IPNetwork network, IPAddress ipaddress)
- {
-
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
-
- return network.Contains(ipaddress);
- }
-
/// <summary>
/// return true is network2 is fully contained in network
/// </summary>
@@ -1201,18 +1189,6 @@ namespace System.Net
return contains;
}
- [Obsolete("static Contains is deprecated, please use instance Contains.")]
- public static bool Contains(IPNetwork network, IPNetwork network2)
- {
-
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
-
- return network.Contains(network2);
- }
-
#endregion
#region overlap
@@ -1245,18 +1221,6 @@ namespace System.Net
return overlap;
}
- [Obsolete("static Overlap is deprecated, please use instance Overlap.")]
- public static bool Overlap(IPNetwork network, IPNetwork network2)
- {
-
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
-
- return network.Overlap(network2);
- }
-
#endregion
#region ToString
@@ -1341,18 +1305,6 @@ namespace System.Net
|| IPNetwork.IANA_CBLK_RESERVED1.Contains(this);
}
- [Obsolete("static IsIANAReserved is deprecated, please use instance IsIANAReserved.")]
- public static bool IsIANAReserved(IPNetwork ipnetwork)
- {
-
- if (ipnetwork == null)
- {
- throw new ArgumentNullException("ipnetwork");
- }
-
- return ipnetwork.IsIANAReserved();
- }
-
#endregion
#region Subnet
@@ -1371,16 +1323,6 @@ namespace System.Net
return ipnetworkCollection;
}
- [Obsolete("static Subnet is deprecated, please use instance Subnet.")]
- public static IPNetworkCollection Subnet(IPNetwork network, byte cidr)
- {
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
- return network.Subnet(cidr);
- }
-
/// <summary>
/// Subnet a network into multiple nets of cidr mask
/// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
@@ -1402,16 +1344,6 @@ namespace System.Net
return true;
}
- [Obsolete("static TrySubnet is deprecated, please use instance TrySubnet.")]
- public static bool TrySubnet(IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
- {
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
- return network.TrySubnet(cidr, out ipnetworkCollection);
- }
-
#if TRAVISCI
public
#else
@@ -1476,12 +1408,6 @@ namespace System.Net
return supernet;
}
- [Obsolete("static Supernet is deprecated, please use instance Supernet.")]
- public static IPNetwork Supernet(IPNetwork network, IPNetwork network2)
- {
- return network.Supernet(network2);
- }
-
/// <summary>
/// Try to supernet two consecutive cidr equal subnet into a single one
/// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
@@ -1500,16 +1426,6 @@ namespace System.Net
return parsed;
}
- [Obsolete("static TrySupernet is deprecated, please use instance TrySupernet.")]
- public static bool TrySupernet(IPNetwork network, IPNetwork network2, out IPNetwork supernet)
- {
- if (network == null)
- {
- throw new ArgumentNullException("network");
- }
- return network.TrySupernet(network2, out supernet);
- }
-
#if TRAVISCI
public
#else
@@ -1920,18 +1836,6 @@ namespace System.Net
return sw.ToString();
}
- [Obsolete("static Print is deprecated, please use instance Print.")]
- public static string Print(IPNetwork ipnetwork)
- {
-
- if (ipnetwork == null)
- {
- throw new ArgumentNullException("ipnetwork");
- }
-
- return ipnetwork.Print();
- }
-
#endregion
#region TryGuessCidr
@@ -2018,12 +1922,6 @@ namespace System.Net
#region ListIPAddress
- [Obsolete("static ListIPAddress is deprecated, please use instance ListIPAddress.")]
- public static IPAddressCollection ListIPAddress(IPNetwork ipnetwork)
- {
- return ipnetwork.ListIPAddress();
- }
-
public IPAddressCollection ListIPAddress()
{
return new IPAddressCollection(this);
@@ -2167,4 +2065,4 @@ namespace System.Net
#endregion
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs
index 4699b5bd4..260d20e35 100644
--- a/Emby.Server.Implementations/Networking/NetworkManager.cs
+++ b/Emby.Server.Implementations/Networking/NetworkManager.cs
@@ -9,7 +9,7 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using System.Numerics;
@@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Networking
}
catch (Exception ex)
{
- Logger.ErrorException("Error binding to NetworkAddressChanged event", ex);
+ Logger.LogError(ex, "Error binding to NetworkAddressChanged event");
}
try
@@ -45,20 +45,20 @@ namespace Emby.Server.Implementations.Networking
}
catch (Exception ex)
{
- Logger.ErrorException("Error binding to NetworkChange_NetworkAvailabilityChanged event", ex);
+ Logger.LogError(ex, "Error binding to NetworkChange_NetworkAvailabilityChanged event");
}
}
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
- Logger.Debug("NetworkAvailabilityChanged");
+ Logger.LogDebug("NetworkAvailabilityChanged");
OnNetworkChanged();
}
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
- Logger.Debug("NetworkAddressChanged");
+ Logger.LogDebug("NetworkAddressChanged");
OnNetworkChanged();
}
@@ -189,7 +189,7 @@ namespace Emby.Server.Implementations.Networking
foreach (var subnet_Match in subnets)
{
- //Logger.Debug("subnet_Match:" + subnet_Match);
+ //logger.LogDebug("subnet_Match:" + subnet_Match);
if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase))
{
@@ -355,13 +355,13 @@ namespace Emby.Server.Implementations.Networking
try
{
var host = uri.DnsSafeHost;
- Logger.Debug("Resolving host {0}", host);
+ Logger.LogDebug("Resolving host {0}", host);
address = GetIpAddresses(host).Result.FirstOrDefault();
if (address != null)
{
- Logger.Debug("{0} resolved to {1}", host, address);
+ Logger.LogDebug("{0} resolved to {1}", host, address);
return IsInLocalNetworkInternal(address.ToString(), false);
}
@@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Networking
}
catch (Exception ex)
{
- Logger.ErrorException("Error resovling hostname", ex);
+ Logger.LogError(ex, "Error resolving hostname");
}
}
}
@@ -399,7 +399,7 @@ namespace Emby.Server.Implementations.Networking
}
catch (Exception ex)
{
- Logger.ErrorException("Error in GetAllNetworkInterfaces", ex);
+ Logger.LogError(ex, "Error in GetAllNetworkInterfaces");
return new List<IPAddress>();
}
@@ -409,7 +409,7 @@ namespace Emby.Server.Implementations.Networking
try
{
// suppress logging because it might be causing nas device wake up
- //Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
+ //logger.LogDebug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
var ipProperties = network.GetIPProperties();
@@ -428,7 +428,7 @@ namespace Emby.Server.Implementations.Networking
}
catch (Exception ex)
{
- Logger.ErrorException("Error querying network interface", ex);
+ Logger.LogError(ex, "Error querying network interface");
return new List<IPAddress>();
}
diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs
deleted file mode 100644
index 38a250593..000000000
--- a/Emby.Server.Implementations/News/NewsEntryPoint.cs
+++ /dev/null
@@ -1,279 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Notifications;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.News;
-using MediaBrowser.Model.Notifications;
-using MediaBrowser.Model.Serialization;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Threading;
-
-namespace Emby.Server.Implementations.News
-{
- public class NewsEntryPoint : IServerEntryPoint
- {
- private ITimer _timer;
- private readonly IHttpClient _httpClient;
- private readonly IApplicationPaths _appPaths;
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
-
- private readonly INotificationManager _notifications;
- private readonly IUserManager _userManager;
-
- private readonly TimeSpan _frequency = TimeSpan.FromHours(24);
- private readonly ITimerFactory _timerFactory;
-
- public NewsEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IJsonSerializer json, INotificationManager notifications, IUserManager userManager, ITimerFactory timerFactory)
- {
- _httpClient = httpClient;
- _appPaths = appPaths;
- _fileSystem = fileSystem;
- _logger = logger;
- _json = json;
- _notifications = notifications;
- _userManager = userManager;
- _timerFactory = timerFactory;
- }
-
- public void Run()
- {
- _timer = _timerFactory.Create(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency);
- }
-
- /// <summary>
- /// Called when [timer fired].
- /// </summary>
- /// <param name="state">The state.</param>
- private async void OnTimerFired(object state)
- {
- var path = Path.Combine(_appPaths.CachePath, "news.json");
-
- try
- {
- await DownloadNews(path).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error downloading news", ex);
- }
- }
-
- private async Task DownloadNews(string path)
- {
- DateTime? lastUpdate = null;
-
- if (_fileSystem.FileExists(path))
- {
- lastUpdate = _fileSystem.GetLastWriteTimeUtc(path);
- }
-
- var requestOptions = new HttpRequestOptions
- {
- Url = "https://github.com/jellyfin/jellyfin",
- Progress = new SimpleProgress<double>(),
- UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36",
- BufferContent = false
- };
-
- using (var response = await _httpClient.SendAsync(requestOptions, "GET").ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- using (var reader = XmlReader.Create(stream))
- {
- var news = ParseRssItems(reader).ToList();
-
- _json.SerializeToFile(news, path);
-
- await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false);
- }
- }
- }
- }
-
- private Task CreateNotifications(List<NewsItem> items, DateTime? lastUpdate, CancellationToken cancellationToken)
- {
- if (lastUpdate.HasValue)
- {
- items = items.Where(i => i.Date.ToUniversalTime() >= lastUpdate.Value)
- .ToList();
- }
-
- var tasks = items.Select(i => _notifications.SendNotification(new NotificationRequest
- {
- Date = i.Date,
- Name = i.Title,
- Description = i.Description,
- Url = i.Link,
- UserIds = _userManager.Users.Select(u => u.Id).ToArray()
-
- }, cancellationToken));
-
- return Task.WhenAll(tasks);
- }
-
- private IEnumerable<NewsItem> ParseRssItems(XmlReader reader)
- {
- reader.MoveToContent();
- reader.Read();
-
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "channel":
- {
- if (!reader.IsEmptyElement)
- {
- using (var subReader = reader.ReadSubtree())
- {
- return ParseFromChannelNode(subReader);
- }
- }
- else
- {
- reader.Read();
- }
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- return new List<NewsItem>();
- }
-
- private IEnumerable<NewsItem> ParseFromChannelNode(XmlReader reader)
- {
- var list = new List<NewsItem>();
-
- reader.MoveToContent();
- reader.Read();
-
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "item":
- {
- if (!reader.IsEmptyElement)
- {
- using (var subReader = reader.ReadSubtree())
- {
- list.Add(ParseItem(subReader));
- }
- }
- else
- {
- reader.Read();
- }
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- return list;
- }
-
- private NewsItem ParseItem(XmlReader reader)
- {
- var item = new NewsItem();
-
- reader.MoveToContent();
- reader.Read();
-
- while (!reader.EOF && reader.ReadState == ReadState.Interactive)
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "title":
- {
- item.Title = reader.ReadElementContentAsString();
- break;
- }
- case "link":
- {
- item.Link = reader.ReadElementContentAsString();
- break;
- }
- case "description":
- {
- item.DescriptionHtml = reader.ReadElementContentAsString();
- item.Description = item.DescriptionHtml.StripHtml();
- break;
- }
- case "pubDate":
- {
- var date = reader.ReadElementContentAsString();
- DateTime parsedDate;
-
- if (DateTime.TryParse(date, out parsedDate))
- {
- item.Date = parsedDate;
- }
- break;
- }
- default:
- {
- reader.Skip();
- break;
- }
- }
- }
- else
- {
- reader.Read();
- }
- }
-
- return item;
- }
-
- public void Dispose()
- {
- if (_timer != null)
- {
- _timer.Dispose();
- _timer = null;
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/News/NewsService.cs b/Emby.Server.Implementations/News/NewsService.cs
deleted file mode 100644
index 80e799634..000000000
--- a/Emby.Server.Implementations/News/NewsService.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.News;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Serialization;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-
-namespace Emby.Server.Implementations.News
-{
- public class NewsService : INewsService
- {
- private readonly IApplicationPaths _appPaths;
- private readonly IJsonSerializer _json;
-
- public NewsService(IApplicationPaths appPaths, IJsonSerializer json)
- {
- _appPaths = appPaths;
- _json = json;
- }
-
- public QueryResult<NewsItem> GetProductNews(NewsQuery query)
- {
- try
- {
- return GetProductNewsInternal(query);
- }
- catch (FileNotFoundException)
- {
- // No biggie
- return new QueryResult<NewsItem>
- {
- Items = new NewsItem[] { }
- };
- }
- catch (IOException)
- {
- // No biggie
- return new QueryResult<NewsItem>
- {
- Items = new NewsItem[] { }
- };
- }
- }
-
- private QueryResult<NewsItem> GetProductNewsInternal(NewsQuery query)
- {
- var path = Path.Combine(_appPaths.CachePath, "news.json");
-
- var items = GetNewsItems(path).OrderByDescending(i => i.Date);
-
- var itemsArray = items.ToArray();
- var count = itemsArray.Length;
-
- if (query.StartIndex.HasValue)
- {
- itemsArray = itemsArray.Skip(query.StartIndex.Value).ToArray();
- }
-
- if (query.Limit.HasValue)
- {
- itemsArray = itemsArray.Take(query.Limit.Value).ToArray();
- }
-
- return new QueryResult<NewsItem>
- {
- Items = itemsArray,
- TotalRecordCount = count
- };
- }
-
- private IEnumerable<NewsItem> GetNewsItems(string path)
- {
- return _json.DeserializeFromFile<List<NewsItem>>(path);
- }
- }
-}
diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
index 1e8d30ab9..470711b9e 100644
--- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs
+++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Playlists;
using System;
using System.Collections.Generic;
@@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.Playlists
parentFolder.AddChild(playlist, CancellationToken.None);
- await playlist.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) { ForceSave = true }, CancellationToken.None)
+ await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, CancellationToken.None)
.ConfigureAwait(false);
if (options.ItemIdList.Length > 0)
@@ -217,7 +217,7 @@ namespace Emby.Server.Implementations.Playlists
SavePlaylistFile(playlist);
}
- _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ForceSave = true
@@ -250,7 +250,7 @@ namespace Emby.Server.Implementations.Playlists
SavePlaylistFile(playlist);
}
- _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
ForceSave = true
diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs
index ce29b52f6..04cf0632c 100644
--- a/Emby.Server.Implementations/ResourceFileManager.cs
+++ b/Emby.Server.Implementations/ResourceFileManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using System;
@@ -59,7 +59,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
- _logger.ErrorException("Error in Path.GetFullPath", ex);
+ _logger.LogError(ex, "Error in Path.GetFullPath");
}
// Don't allow file system access outside of the source folder
diff --git a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs
index 8ed2dbaed..09dcc320a 100644
--- a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -44,9 +44,9 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary>
/// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
/// </summary>
- public ChapterImagesTask(ILogManager logManager, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem)
+ public ChapterImagesTask(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem)
{
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
_libraryManager = libraryManager;
_itemRepo = itemRepo;
_appPaths = appPaths;
@@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
previouslyFailedImages = new List<string>();
}
- var directoryService = new DirectoryService(_fileSystem);
+ var directoryService = new DirectoryService(_logger, _fileSystem);
foreach (var video in videos)
{
diff --git a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs
index a2779c7cd..afcee02e5 100644
--- a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs
@@ -2,7 +2,7 @@
using System.Globalization;
using System.Threading;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
@@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var dueTime = triggerDate - now;
- logger.Info("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ logger.LogInformation("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs
index dcccb252a..5f6a0dfe6 100644
--- a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs
@@ -2,7 +2,7 @@
using System.Linq;
using System.Threading;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
index eeb38bf54..0bebca8fc 100644
--- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
@@ -5,12 +5,11 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
@@ -146,7 +145,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
catch (Exception ex)
{
- Logger.ErrorException("Error deserializing {0}", ex, path);
+ Logger.LogError(ex, "Error deserializing {path}", path);
}
_readFromFile = true;
}
@@ -360,7 +359,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
return;
}
- Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name);
+ Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
trigger.Stop();
@@ -408,7 +407,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
CurrentCancellationTokenSource = new CancellationTokenSource();
- Logger.Info("Executing {0}", Name);
+ Logger.LogInformation("Executing {0}", Name);
((TaskManager)TaskManager).OnTaskExecuting(this);
@@ -436,7 +435,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
}
catch (Exception ex)
{
- Logger.ErrorException("Error", ex);
+ Logger.LogError(ex, "Error");
failureException = ex;
@@ -465,11 +464,10 @@ namespace Emby.Server.Implementations.ScheduledTasks
CurrentProgress = e;
- EventHelper.FireEventIfNotNull(TaskProgress, this, new GenericEventArgs<double>
+ TaskProgress?.Invoke(this, new GenericEventArgs<double>
{
Argument = e
-
- }, Logger);
+ });
}
/// <summary>
@@ -493,7 +491,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
if (State == TaskState.Running)
{
- Logger.Info("Attempting to cancel Scheduled Task {0}", Name);
+ Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
CurrentCancellationTokenSource.Cancel();
}
}
@@ -614,7 +612,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
var elapsedTime = endTime - startTime;
- Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
+ Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
var result = new TaskResult
{
@@ -664,12 +662,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
try
{
- Logger.Info(Name + ": Cancelling");
+ Logger.LogInformation(Name + ": Cancelling");
token.Cancel();
}
catch (Exception ex)
{
- Logger.ErrorException("Error calling CancellationToken.Cancel();", ex);
+ Logger.LogError(ex, "Error calling CancellationToken.Cancel();");
}
}
var task = _currentTask;
@@ -677,21 +675,21 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
try
{
- Logger.Info(Name + ": Waiting on Task");
+ Logger.LogInformation(Name + ": Waiting on Task");
var exited = Task.WaitAll(new[] { task }, 2000);
if (exited)
{
- Logger.Info(Name + ": Task exited");
+ Logger.LogInformation(Name + ": Task exited");
}
else
{
- Logger.Info(Name + ": Timed out waiting for task to stop");
+ Logger.LogInformation(Name + ": Timed out waiting for task to stop");
}
}
catch (Exception ex)
{
- Logger.ErrorException("Error calling Task.WaitAll();", ex);
+ Logger.LogError(ex, "Error calling Task.WaitAll();");
}
}
@@ -699,12 +697,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
try
{
- Logger.Debug(Name + ": Disposing CancellationToken");
+ Logger.LogDebug(Name + ": Disposing CancellationToken");
token.Dispose();
}
catch (Exception ex)
{
- Logger.ErrorException("Error calling CancellationToken.Dispose();", ex);
+ Logger.LogError(ex, "Error calling CancellationToken.Dispose();");
}
}
if (wassRunning)
diff --git a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs
index 20a4304cc..35366a044 100644
--- a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs
@@ -1,7 +1,7 @@
using System;
using System.Threading.Tasks;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs
index c4623bf5b..def142f88 100644
--- a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs
@@ -1,7 +1,7 @@
using System;
using System.Threading.Tasks;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs
deleted file mode 100644
index 0c9eb0f1b..000000000
--- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs
+++ /dev/null
@@ -1,128 +0,0 @@
-using MediaBrowser.Common;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Logging;
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Model.Tasks;
-
-namespace Emby.Server.Implementations.ScheduledTasks
-{
- /// <summary>
- /// Plugin Update Task
- /// </summary>
- public class SystemUpdateTask : IScheduledTask
- {
- /// <summary>
- /// The _app host
- /// </summary>
- private readonly IApplicationHost _appHost;
-
- /// <summary>
- /// Gets or sets the configuration manager.
- /// </summary>
- /// <value>The configuration manager.</value>
- private IConfigurationManager ConfigurationManager { get; set; }
- /// <summary>
- /// Gets or sets the logger.
- /// </summary>
- /// <value>The logger.</value>
- private ILogger Logger { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SystemUpdateTask" /> class.
- /// </summary>
- /// <param name="appHost">The app host.</param>
- /// <param name="configurationManager">The configuration manager.</param>
- /// <param name="logger">The logger.</param>
- public SystemUpdateTask(IApplicationHost appHost, IConfigurationManager configurationManager, ILogger logger)
- {
- _appHost = appHost;
- ConfigurationManager = configurationManager;
- Logger = logger;
- }
-
- /// <summary>
- /// Creates the triggers that define when the task will run
- /// </summary>
- /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
- {
- return new[] {
-
- // At startup
- new TaskTriggerInfo {Type = TaskTriggerInfo.TriggerStartup},
-
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
- };
- }
-
- /// <summary>
- /// Returns the task to be executed
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="progress">The progress.</param>
- /// <returns>Task.</returns>
- public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
- {
- // Create a progress object for the update check
- var updateInfo = await _appHost.CheckForApplicationUpdate(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
-
- if (!updateInfo.IsUpdateAvailable)
- {
- Logger.Debug("No application update available.");
- return;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- if (!_appHost.CanSelfUpdate) return;
-
- if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate)
- {
- Logger.Info("Update Revision {0} available. Updating...", updateInfo.AvailableVersion);
-
- await _appHost.UpdateApplication(updateInfo.Package, cancellationToken, progress).ConfigureAwait(false);
- }
- else
- {
- Logger.Info("A new version of " + _appHost.Name + " is available.");
- }
- }
-
- /// <summary>
- /// Gets the name of the task
- /// </summary>
- /// <value>The name.</value>
- public string Name
- {
- get { return "Check for application updates"; }
- }
-
- /// <summary>
- /// Gets the description.
- /// </summary>
- /// <value>The description.</value>
- public string Description
- {
- get { return "Downloads and installs application updates."; }
- }
-
- /// <summary>
- /// Gets the category.
- /// </summary>
- /// <value>The category.</value>
- public string Category
- {
- get { return "Application"; }
- }
-
- public string Key
- {
- get { return "SystemUpdateTask"; }
- }
- }
-}
diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
index 8963693ab..361c31acb 100644
--- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
@@ -1,17 +1,16 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Events;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
-using System.IO;
namespace Emby.Server.Implementations.ScheduledTasks
{
@@ -185,7 +184,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
+ Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
}
else
{
@@ -217,13 +216,13 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
+ Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
}
else
{
var type = scheduledTask.ScheduledTask.GetType();
- Logger.Info("Queueing task {0}", type.Name);
+ Logger.LogInformation("Queueing task {0}", type.Name);
lock (_taskQueue)
{
@@ -246,7 +245,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
if (scheduledTask == null)
{
- Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
+ Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
}
else
{
@@ -263,7 +262,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{
var type = task.ScheduledTask.GetType();
- Logger.Info("Queueing task {0}", type.Name);
+ Logger.LogInformation("Queueing task {0}", type.Name);
lock (_taskQueue)
{
@@ -331,11 +330,10 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="task">The task.</param>
internal void OnTaskExecuting(IScheduledTaskWorker task)
{
- EventHelper.FireEventIfNotNull(TaskExecuting, this, new GenericEventArgs<IScheduledTaskWorker>
+ TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>
{
Argument = task
-
- }, Logger);
+ });
}
/// <summary>
@@ -345,12 +343,11 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="result">The result.</param>
internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
{
- EventHelper.FireEventIfNotNull(TaskCompleted, task, new TaskCompletionEventArgs
+ TaskCompleted?.Invoke(task, new TaskCompletionEventArgs
{
Result = result,
Task = task
-
- }, Logger);
+ });
ExecuteQueuedTasks();
}
@@ -360,7 +357,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary>
private void ExecuteQueuedTasks()
{
- Logger.Info("ExecuteQueuedTasks");
+ Logger.LogInformation("ExecuteQueuedTasks");
// Execute queued tasks
lock (_taskQueue)
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
index 05fb08447..c60f59ce4 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
@@ -6,7 +6,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks.Tasks
@@ -132,11 +132,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
}
catch (UnauthorizedAccessException ex)
{
- _logger.ErrorException("Error deleting directory {0}", ex, directory);
+ _logger.LogError(ex, "Error deleting directory {path}", directory);
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting directory {0}", ex, directory);
+ _logger.LogError(ex, "Error deleting directory {path}", directory);
}
}
}
@@ -150,11 +150,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
}
catch (UnauthorizedAccessException ex)
{
- _logger.ErrorException("Error deleting file {0}", ex, path);
+ _logger.LogError(ex, "Error deleting file {path}", path);
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting file {0}", ex, path);
+ _logger.LogError(ex, "Error deleting file {path}", path);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
index d5a7ccadb..b754d7cb5 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
@@ -56,7 +56,8 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
// Delete log files more than n days old
var minDateModified = DateTime.UtcNow.AddDays(-ConfigurationManager.CommonConfiguration.LogFileRetentionDays);
- var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, true)
+ // Only delete the .txt log files, the *.log files created by serilog get managed by itself
+ var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, new[] { ".txt" }, true, true)
.Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
.ToList();
@@ -64,8 +65,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
foreach (var file in filesToDelete)
{
- double percent = index;
- percent /= filesToDelete.Count;
+ double percent = index / filesToDelete.Count;
progress.Report(100 * percent);
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs
deleted file mode 100644
index fbc3a309e..000000000
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Tasks;
-
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
-{
- /// <summary>
- /// Class ReloadLoggerFileTask
- /// </summary>
- public class ReloadLoggerFileTask : IScheduledTask, IConfigurableScheduledTask
- {
- /// <summary>
- /// Gets or sets the log manager.
- /// </summary>
- /// <value>The log manager.</value>
- private ILogManager LogManager { get; set; }
- /// <summary>
- /// Gets or sets the configuration manager.
- /// </summary>
- /// <value>The configuration manager.</value>
- private IConfigurationManager ConfigurationManager { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ReloadLoggerFileTask" /> class.
- /// </summary>
- /// <param name="logManager">The logManager.</param>
- /// <param name="configurationManager">The configuration manager.</param>
- public ReloadLoggerFileTask(ILogManager logManager, IConfigurationManager configurationManager)
- {
- LogManager = logManager;
- ConfigurationManager = configurationManager;
- }
-
- /// <summary>
- /// Gets the default triggers.
- /// </summary>
- /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
- {
- var trigger = new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, TimeOfDayTicks = TimeSpan.FromHours(0).Ticks }; //12am
-
- return new[] { trigger };
- }
-
- /// <summary>
- /// Executes the internal.
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="progress">The progress.</param>
- /// <returns>Task.</returns>
- public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- progress.Report(0);
-
- return LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
- ? LogSeverity.Debug
- : LogSeverity.Info, cancellationToken);
- }
-
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name
- {
- get { return "Rotate log file"; }
- }
-
- public string Key { get; }
-
- /// <summary>
- /// Gets the description.
- /// </summary>
- /// <value>The description.</value>
- public string Description
- {
- get { return "Moves logging to a new file to help reduce log file sizes."; }
- }
-
- /// <summary>
- /// Gets the category.
- /// </summary>
- /// <value>The category.</value>
- public string Category
- {
- get { return "Application"; }
- }
-
- public bool IsHidden
- {
- get { return false; }
- }
-
- public bool IsEnabled
- {
- get { return true; }
- }
-
- public bool IsLogged
- {
- get { return true; }
- }
- }
-}
diff --git a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs
index 82b449917..e694e0855 100644
--- a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs
@@ -1,7 +1,7 @@
using System;
using System.Threading;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs
index f75eb6364..228d511ce 100644
--- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs
+++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs
@@ -7,7 +7,7 @@ using System.Threading;
using Emby.Server.Implementations.Data;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Security;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using SQLitePCL.pretty;
using MediaBrowser.Model.Extensions;
@@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Security
}
catch (Exception ex)
{
- Logger.ErrorException("Error migrating authentication database", ex);
+ Logger.LogError(ex, "Error migrating authentication database");
}
}
diff --git a/Emby.Server.Implementations/Security/PluginSecurityManager.cs b/Emby.Server.Implementations/Security/PluginSecurityManager.cs
index 8d8d6700e..2b1494c39 100644
--- a/Emby.Server.Implementations/Security/PluginSecurityManager.cs
+++ b/Emby.Server.Implementations/Security/PluginSecurityManager.cs
@@ -12,7 +12,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
@@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.Security
/// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
/// </summary>
public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
- IApplicationPaths appPaths, ILogManager logManager, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
+ IApplicationPaths appPaths, ILoggerFactory loggerFactory, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
{
if (httpClient == null)
{
@@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Security
_appPaths = appPaths;
_fileSystem = fileSystem;
_cryptographyProvider = cryptographyProvider;
- _logger = logManager.GetLogger("SecurityManager");
+ _logger = loggerFactory.CreateLogger("SecurityManager");
}
/// <summary>
@@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.Security
if (reg == null)
{
var msg = "Result from appstore registration was null.";
- _logger.Error(msg);
+ _logger.LogError(msg);
throw new ArgumentException(msg);
}
if (!String.IsNullOrEmpty(reg.key))
@@ -150,18 +150,15 @@ namespace Emby.Server.Implementations.Security
SaveAppStoreInfo(parameters);
throw;
}
- catch (HttpException e)
+ catch (HttpException ex)
{
- _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
+ _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
- if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired)
- {
- }
throw new Exception("Error registering store sale");
}
- catch (Exception e)
+ catch (Exception ex)
{
- _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
+ _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
SaveAppStoreInfo(parameters);
//TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
throw new Exception("Error registering store sale");
diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs
index 26371d21d..e28acd769 100644
--- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs
+++ b/Emby.Server.Implementations/Serialization/JsonSerializer.cs
@@ -1,7 +1,7 @@
using System;
using System.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System.Threading.Tasks;
@@ -69,7 +69,7 @@ namespace Emby.Common.Implementations.Serialization
private Stream OpenFile(string path)
{
- //_logger.Debug("Deserializing file {0}", path);
+ //_logger.LogDebug("Deserializing file {0}", path);
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072);
}
@@ -136,19 +136,15 @@ namespace Emby.Common.Implementations.Serialization
return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream);
}
- public async Task<T> DeserializeFromStreamAsync<T>(Stream stream)
+ public Task<T> DeserializeFromStreamAsync<T>(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
- using (var reader = new StreamReader(stream))
- {
- var json = await reader.ReadToEndAsync().ConfigureAwait(false);
- return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(json);
- }
+ return ServiceStack.Text.JsonSerializer.DeserializeFromStreamAsync<T>(stream);
}
/// <summary>
diff --git a/Emby.Server.Implementations/Serialization/XmlSerializer.cs b/Emby.Server.Implementations/Serialization/XmlSerializer.cs
index e0603a01f..dfc324919 100644
--- a/Emby.Server.Implementations/Serialization/XmlSerializer.cs
+++ b/Emby.Server.Implementations/Serialization/XmlSerializer.cs
@@ -4,7 +4,7 @@ using System.IO;
using System.Xml;
using System.Xml.Serialization;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
namespace Emby.Server.Implementations.Serialization
@@ -90,7 +90,7 @@ namespace Emby.Server.Implementations.Serialization
/// <param name="file">The file.</param>
public void SerializeToFile(object obj, string file)
{
- _logger.Debug("Serializing to file {0}", file);
+ _logger.LogDebug("Serializing to file {0}", file);
using (var stream = new FileStream(file, FileMode.Create))
{
SerializeToStream(obj, stream);
@@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.Serialization
/// <returns>System.Object.</returns>
public object DeserializeFromFile(Type type, string file)
{
- _logger.Debug("Deserializing file {0}", file);
+ _logger.LogDebug("Deserializing file {0}", file);
using (var stream = _fileSystem.OpenRead(file))
{
return DeserializeFromStream(type, stream);
diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs
index 1686a548b..8a0f2671a 100644
--- a/Emby.Server.Implementations/ServerApplicationPaths.cs
+++ b/Emby.Server.Implementations/ServerApplicationPaths.cs
@@ -13,8 +13,13 @@ namespace Emby.Server.Implementations
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationPaths" /> class.
/// </summary>
- public ServerApplicationPaths(string programDataPath, string appFolderPath, string applicationResourcesPath)
- : base(programDataPath, appFolderPath)
+ public ServerApplicationPaths(
+ string programDataPath,
+ string appFolderPath,
+ string applicationResourcesPath,
+ string logDirectoryPath = null,
+ string configurationDirectoryPath = null)
+ : base(programDataPath, appFolderPath, logDirectoryPath, configurationDirectoryPath)
{
ApplicationResourcesPath = applicationResourcesPath;
}
diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs
index 3726c9f6b..46af83128 100644
--- a/Emby.Server.Implementations/Services/ServiceController.cs
+++ b/Emby.Server.Implementations/Services/ServiceController.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.Services
@@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.Services
pathsAtFirstMatch.Add(restPath);
}
- public RestPath GetRestPathForRequest(string httpMethod, string pathInfo, ILogger logger)
+ public RestPath GetRestPathForRequest(string httpMethod, string pathInfo)
{
var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo);
@@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.Services
RestPath bestMatch = null;
foreach (var restPath in firstMatches)
{
- var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger);
+ var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
if (score > bestScore)
{
bestScore = score;
@@ -140,7 +140,7 @@ namespace Emby.Server.Implementations.Services
RestPath bestMatch = null;
foreach (var restPath in firstMatches)
{
- var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger);
+ var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
if (score > bestScore)
{
bestScore = score;
@@ -183,4 +183,4 @@ namespace Emby.Server.Implementations.Services
}
}
-} \ No newline at end of file
+}
diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs
index e76857a8d..f5fcb5fe6 100644
--- a/Emby.Server.Implementations/Services/ServiceHandler.cs
+++ b/Emby.Server.Implementations/Services/ServiceHandler.cs
@@ -4,7 +4,7 @@ using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.Services
@@ -24,11 +24,11 @@ namespace Emby.Server.Implementations.Services
return Task.FromResult(host.CreateInstance(requestType));
}
- public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType)
+ public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, out string contentType)
{
pathInfo = GetSanitizedPathInfo(pathInfo, out contentType);
- return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo, logger);
+ return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo);
}
public static string GetSanitizedPathInfo(string pathInfo, out string contentType)
@@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Services
if (this.RestPath == null)
{
string contentType;
- this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, new NullLogger(), out contentType);
+ this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, out contentType);
if (contentType != null)
ResponseContentType = contentType;
diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs
index f0e80c216..ac2af3eaf 100644
--- a/Emby.Server.Implementations/Services/ServicePath.cs
+++ b/Emby.Server.Implementations/Services/ServicePath.cs
@@ -4,7 +4,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Services
@@ -309,10 +309,10 @@ namespace Emby.Server.Implementations.Services
private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
- public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger)
+ public int MatchScore(string httpMethod, string[] withPathInfoParts)
{
int wildcardMatchCount;
- var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount);
+ var isMatch = IsMatch(httpMethod, withPathInfoParts, out wildcardMatchCount);
if (!isMatch)
{
return -1;
@@ -348,31 +348,27 @@ namespace Emby.Server.Implementations.Services
/// For performance withPathInfoParts should already be a lower case string
/// to minimize redundant matching operations.
/// </summary>
- public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount)
+ public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
{
wildcardMatchCount = 0;
if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
{
- //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
- return false;
+ return false;
}
if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
{
- //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs);
return false;
}
if (!ExplodeComponents(ref withPathInfoParts))
{
- //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
return false;
}
if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
{
- //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
return false;
}
@@ -393,7 +389,6 @@ namespace Emby.Server.Implementations.Services
// Ensure there are still enough parts left to match the remainder
if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
{
- //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts));
return false;
}
}
@@ -416,7 +411,6 @@ namespace Emby.Server.Implementations.Services
if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch))
{
- //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch);
return false;
}
pathIx++;
diff --git a/Emby.Server.Implementations/Session/FirebaseSessionController.cs b/Emby.Server.Implementations/Session/FirebaseSessionController.cs
deleted file mode 100644
index cfe513305..000000000
--- a/Emby.Server.Implementations/Session/FirebaseSessionController.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Net;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Serialization;
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Text;
-using MediaBrowser.Common;
-
-namespace Emby.Server.Implementations.Session
-{
- public class FirebaseSessionController : ISessionController
- {
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _json;
- private readonly ISessionManager _sessionManager;
-
- public SessionInfo Session { get; private set; }
-
- private readonly string _token;
-
- private IApplicationHost _appHost;
- private string _senderId;
- private string _applicationId;
-
- public FirebaseSessionController(IHttpClient httpClient,
- IApplicationHost appHost,
- IJsonSerializer json,
- SessionInfo session,
- string token, ISessionManager sessionManager)
- {
- _httpClient = httpClient;
- _json = json;
- _appHost = appHost;
- Session = session;
- _token = token;
- _sessionManager = sessionManager;
-
- _applicationId = _appHost.GetValue("firebase_applicationid");
- _senderId = _appHost.GetValue("firebase_senderid");
- }
-
- public static bool IsSupported(IApplicationHost appHost)
- {
- return !string.IsNullOrEmpty(appHost.GetValue("firebase_applicationid")) && !string.IsNullOrEmpty(appHost.GetValue("firebase_senderid"));
- }
-
- public bool IsSessionActive
- {
- get
- {
- return (DateTime.UtcNow - Session.LastActivityDate).TotalDays <= 3;
- }
- }
-
- public bool SupportsMediaControl
- {
- get { return true; }
- }
-
- public async Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
- {
- if (!IsSessionActive)
- {
- return;
- }
-
- if (string.IsNullOrEmpty(_senderId) || string.IsNullOrEmpty(_applicationId))
- {
- return;
- }
-
- foreach (var controller in allControllers)
- {
- // Don't send if there's an active web socket connection
- if ((controller is WebSocketController) && controller.IsSessionActive)
- {
- return;
- }
- }
-
- var msg = new WebSocketMessage<T>
- {
- Data = data,
- MessageType = name,
- MessageId = messageId,
- ServerId = _appHost.SystemId
- };
-
- var req = new FirebaseBody<T>
- {
- to = _token,
- data = msg
- };
-
- var byteArray = Encoding.UTF8.GetBytes(_json.SerializeToString(req));
-
- var enableLogging = false;
-
-#if DEBUG
- enableLogging = true;
-#endif
-
- var options = new HttpRequestOptions
- {
- Url = "https://fcm.googleapis.com/fcm/send",
- RequestContentType = "application/json",
- RequestContentBytes = byteArray,
- CancellationToken = cancellationToken,
- LogRequest = enableLogging,
- LogResponse = enableLogging,
- LogErrors = enableLogging
- };
-
- options.RequestHeaders["Authorization"] = string.Format("key={0}", _applicationId);
- options.RequestHeaders["Sender"] = string.Format("id={0}", _senderId);
-
- using (var response = await _httpClient.Post(options).ConfigureAwait(false))
- {
-
- }
- }
- }
-
- internal class FirebaseBody<T>
- {
- public string to { get; set; }
- public WebSocketMessage<T> data { get; set; }
- }
-}
diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs
index a2102dc45..7321e9f86 100644
--- a/Emby.Server.Implementations/Session/SessionManager.cs
+++ b/Emby.Server.Implementations/Session/SessionManager.cs
@@ -15,10 +15,9 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
-using MediaBrowser.Model.Users;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -248,18 +247,17 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error updating user", ex);
+ _logger.LogError("Error updating user", ex);
}
}
}
if ((activityDate - lastActivityDate).TotalSeconds > 10)
{
- EventHelper.FireEventIfNotNull(SessionActivity, this, new SessionEventArgs
+ SessionActivity?.Invoke(this, new SessionEventArgs
{
SessionInfo = session
-
- }, _logger);
+ });
}
return session;
@@ -528,7 +526,7 @@ namespace Emby.Server.Implementations.Session
foreach (var session in idle)
{
- _logger.Debug("Session {0} has gone idle while playing", session.Id);
+ _logger.LogDebug("Session {0} has gone idle while playing", session.Id);
try
{
@@ -543,7 +541,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.Debug("Error calling OnPlaybackStopped", ex);
+ _logger.LogDebug("Error calling OnPlaybackStopped", ex);
}
}
@@ -693,7 +691,7 @@ namespace Emby.Server.Implementations.Session
}
}
- EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
+ PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
@@ -707,8 +705,7 @@ namespace Emby.Server.Implementations.Session
PlaySessionId = info.PlaySessionId,
IsAutomated = isAutomated,
Session = session
-
- }, _logger);
+ });
if (!isAutomated)
{
@@ -847,7 +844,7 @@ namespace Emby.Server.Implementations.Session
{
var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
- _logger.Info("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
+ _logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
session.Client,
session.ApplicationVersion,
info.Item.Name,
@@ -882,7 +879,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error closing live stream", ex);
+ _logger.LogError("Error closing live stream", ex);
}
}
@@ -1095,7 +1092,7 @@ namespace Emby.Server.Implementations.Session
if (item == null)
{
- _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
+ _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
return new List<BaseItem>();
}
@@ -1151,7 +1148,7 @@ namespace Emby.Server.Implementations.Session
if (item == null)
{
- _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
+ _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
return new List<BaseItem>();
}
@@ -1222,7 +1219,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
+ _logger.LogError("Error in SendRestartRequiredNotification.", ex);
}
}, cancellationToken)).ToArray();
@@ -1249,7 +1246,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
+ _logger.LogError("Error in SendServerShutdownNotification.", ex);
}
}, cancellationToken)).ToArray();
@@ -1266,7 +1263,7 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
- _logger.Debug("Beginning SendServerRestartNotification");
+ _logger.LogDebug("Beginning SendServerRestartNotification");
var sessions = Sessions.ToList();
@@ -1278,7 +1275,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error in SendServerRestartNotification.", ex);
+ _logger.LogError("Error in SendServerRestartNotification.", ex);
}
}, cancellationToken)).ToArray();
@@ -1399,7 +1396,7 @@ namespace Emby.Server.Implementations.Session
if (result == null)
{
- EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
+ AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
throw new SecurityException("Invalid user or password entered.");
}
@@ -1424,7 +1421,7 @@ namespace Emby.Server.Implementations.Session
ServerId = _appHost.SystemId
};
- EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationResult>(returnResult), _logger);
+ AuthenticationSucceeded?.Invoke(this, new GenericEventArgs<AuthenticationResult>(returnResult));
return returnResult;
}
@@ -1462,7 +1459,7 @@ namespace Emby.Server.Implementations.Session
if (existing != null)
{
- _logger.Info("Reissuing access token: " + existing.AccessToken);
+ _logger.LogInformation("Reissuing access token: " + existing.AccessToken);
return existing.AccessToken;
}
@@ -1481,7 +1478,7 @@ namespace Emby.Server.Implementations.Session
UserName = user.Name
};
- _logger.Info("Creating new access token for user {0}", user.Id);
+ _logger.LogInformation("Creating new access token for user {0}", user.Id);
_authRepo.Create(newToken);
return newToken.AccessToken;
@@ -1513,7 +1510,7 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
- _logger.Info("Logging out access token {0}", existing.AccessToken);
+ _logger.LogInformation("Logging out access token {0}", existing.AccessToken);
_authRepo.Delete(existing);
@@ -1529,7 +1526,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting session ended", ex);
+ _logger.LogError("Error reporting session ended", ex);
}
}
}
@@ -1577,21 +1574,12 @@ namespace Emby.Server.Implementations.Session
{
session.Capabilities = capabilities;
- if (!string.IsNullOrEmpty(capabilities.PushToken))
- {
- if (string.Equals(capabilities.PushTokenType, "firebase", StringComparison.OrdinalIgnoreCase) && FirebaseSessionController.IsSupported(_appHost))
- {
- EnsureFirebaseController(session, capabilities.PushToken);
- }
- }
-
if (saveCapabilities)
{
- EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
+ CapabilitiesChanged?.Invoke(this, new SessionEventArgs
{
SessionInfo = session
-
- }, _logger);
+ });
try
{
@@ -1599,16 +1587,11 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving device capabilities", ex);
+ _logger.LogError("Error saving device capabilities", ex);
}
}
}
- private void EnsureFirebaseController(SessionInfo session, string token)
- {
- session.EnsureController<FirebaseSessionController>(s => new FirebaseSessionController(_httpClient, _appHost, _jsonSerializer, s, token, this));
- }
-
private ClientCapabilities GetSavedCapabilities(string deviceId)
{
return _deviceManager.GetCapabilities(deviceId);
@@ -1692,7 +1675,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting {0} image info", ex, type);
+ _logger.LogError("Error getting {0} image info", ex, type);
return null;
}
}
@@ -1818,7 +1801,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message", ex);
+ _logger.LogError("Error sending message", ex);
}
}, cancellationToken)).ToArray();
@@ -1840,7 +1823,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message", ex);
+ _logger.LogError("Error sending message", ex);
}
}, cancellationToken)).ToArray();
@@ -1862,7 +1845,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message", ex);
+ _logger.LogError("Error sending message", ex);
}
}, cancellationToken)).ToArray();
@@ -1886,7 +1869,7 @@ namespace Emby.Server.Implementations.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message", ex);
+ _logger.LogError("Error sending message", ex);
}
}, cancellationToken)).ToArray();
diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
index 9ab4753fb..3bb022b32 100644
--- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
+++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
using System;
@@ -40,14 +40,14 @@ namespace Emby.Server.Implementations.Session
/// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
/// </summary>
/// <param name="sessionManager">The session manager.</param>
- /// <param name="logManager">The log manager.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
/// <param name="json">The json.</param>
/// <param name="httpServer">The HTTP server.</param>
/// <param name="serverManager">The server manager.</param>
- public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json, IHttpServer httpServer)
+ public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer)
{
_sessionManager = sessionManager;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
_json = json;
_httpServer = httpServer;
httpServer.WebSocketConnected += _serverManager_WebSocketConnected;
@@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Session
}
else
{
- _logger.Warn("Unable to determine session based on url: {0}", e.Argument.Url);
+ _logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url);
}
}
diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs
index ddac9660f..bdae5cf8f 100644
--- a/Emby.Server.Implementations/Session/WebSocketController.cs
+++ b/Emby.Server.Implementations/Session/WebSocketController.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.System;
diff --git a/Emby.Server.Implementations/StartupOptions.cs b/Emby.Server.Implementations/StartupOptions.cs
index 159c36248..2114d85bf 100644
--- a/Emby.Server.Implementations/StartupOptions.cs
+++ b/Emby.Server.Implementations/StartupOptions.cs
@@ -1,33 +1,30 @@
using System;
-using System.Collections.Generic;
using System.Linq;
namespace Emby.Server.Implementations
{
public class StartupOptions
{
- private readonly List<string> _options;
+ private readonly string[] _options;
public StartupOptions(string[] commandLineArgs)
{
- _options = commandLineArgs.ToList();
+ _options = commandLineArgs;
}
public bool ContainsOption(string option)
- {
- return _options.Contains(option, StringComparer.OrdinalIgnoreCase);
- }
+ => _options.Contains(option, StringComparer.OrdinalIgnoreCase);
public string GetOption(string name)
{
- var index = _options.IndexOf(name);
+ int index = Array.IndexOf(_options, name);
- if (index != -1)
+ if (index == -1)
{
- return _options.ElementAtOrDefault(index + 1);
+ return null;
}
- return null;
+ return _options.ElementAtOrDefault(index + 1);
}
}
}
diff --git a/Emby.Server.Implementations/SystemEvents.cs b/Emby.Server.Implementations/SystemEvents.cs
index c1e6dc1da..578338aee 100644
--- a/Emby.Server.Implementations/SystemEvents.cs
+++ b/Emby.Server.Implementations/SystemEvents.cs
@@ -1,7 +1,6 @@
using System;
-using MediaBrowser.Common.Events;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations
{
diff --git a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs
index ea87a9539..f30c181a0 100644
--- a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs
+++ b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs
@@ -1,7 +1,7 @@
using System;
using System.Text;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Text;
using NLangDetect.Core;
@@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.TextEncoding
if (!string.IsNullOrWhiteSpace(language))
{
- _logger.Debug("Text language detected as {0}", language);
+ _logger.LogDebug("Text language detected as {0}", language);
}
}
@@ -165,7 +165,7 @@ namespace Emby.Server.Implementations.TextEncoding
throw new ArgumentNullException("charset");
}
- _logger.Debug("Getting encoding object for character set: {0}", charset);
+ _logger.LogDebug("Getting encoding object for character set: {0}", charset);
try
{
@@ -174,7 +174,7 @@ namespace Emby.Server.Implementations.TextEncoding
catch (ArgumentException)
{
charset = charset.Replace("-", string.Empty);
- _logger.Debug("Getting encoding object for character set: {0}", charset);
+ _logger.LogDebug("Getting encoding object for character set: {0}", charset);
return Encoding.GetEncoding(charset);
}
diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs
index f195ca710..275bd83ea 100644
--- a/Emby.Server.Implementations/Udp/UdpServer.cs
+++ b/Emby.Server.Implementations/Udp/UdpServer.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller;
using MediaBrowser.Model.ApiClient;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
@@ -40,6 +40,7 @@ namespace Emby.Server.Implementations.Udp
_json = json;
_socketFactory = socketFactory;
+ AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message);
AddMessageResponder("who is EmbyServer?", true, RespondToV2Message);
AddMessageResponder("who is MediaBrowserServer_v2?", false, RespondToV2Message);
}
@@ -79,7 +80,7 @@ namespace Emby.Server.Implementations.Udp
}
catch (Exception ex)
{
- _logger.ErrorException("Error in OnMessageReceived", ex);
+ _logger.LogError(ex, "Error in OnMessageReceived");
}
}
}
@@ -127,7 +128,7 @@ namespace Emby.Server.Implementations.Udp
}
else
{
- _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
+ _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
}
}
@@ -171,7 +172,7 @@ namespace Emby.Server.Implementations.Udp
}
catch (Exception ex)
{
- _logger.ErrorException("Error receiving udp message", ex);
+ _logger.LogError(ex, "Error receiving udp message");
}
}
@@ -193,7 +194,7 @@ namespace Emby.Server.Implementations.Udp
}
catch (Exception ex)
{
- _logger.ErrorException("Error receiving udp message", ex);
+ _logger.LogError(ex, "Error receiving udp message");
}
BeginReceive();
@@ -224,7 +225,7 @@ namespace Emby.Server.Implementations.Udp
}
catch (Exception ex)
{
- _logger.ErrorException("Error handling UDP message", ex);
+ _logger.LogError(ex, "Error handling UDP message");
}
}
@@ -274,7 +275,7 @@ namespace Emby.Server.Implementations.Udp
{
await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false);
- _logger.Info("Udp message sent to {0}", remoteEndPoint);
+ _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint);
}
catch (OperationCanceledException)
{
@@ -282,7 +283,7 @@ namespace Emby.Server.Implementations.Udp
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
+ _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint);
}
}
}
diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs
index a23166647..82b61c15a 100644
--- a/Emby.Server.Implementations/Updates/InstallationManager.cs
+++ b/Emby.Server.Implementations/Updates/InstallationManager.cs
@@ -7,7 +7,6 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Events;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Progress;
@@ -16,7 +15,7 @@ using MediaBrowser.Common.Updates;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
using MediaBrowser.Controller.Configuration;
@@ -60,7 +59,7 @@ namespace Emby.Server.Implementations.Updates
/// <param name="plugin">The plugin.</param>
private void OnPluginUninstalled(IPlugin plugin)
{
- EventHelper.FireEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
+ PluginUninstalled?.Invoke(this, new GenericEventArgs<IPlugin> { Argument = plugin });
}
#endregion
@@ -76,9 +75,9 @@ namespace Emby.Server.Implementations.Updates
/// <param name="newVersion">The new version.</param>
private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
{
- _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification);
+ _logger.LogInformation("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification);
- EventHelper.FireEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
+ PluginUpdated?.Invoke(this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) });
_applicationHost.NotifyPendingRestart();
}
@@ -95,9 +94,9 @@ namespace Emby.Server.Implementations.Updates
/// <param name="package">The package.</param>
private void OnPluginInstalled(PackageVersionInfo package)
{
- _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
+ _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification);
- EventHelper.FireEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
+ PluginInstalled?.Invoke(this, new GenericEventArgs<PackageVersionInfo> { Argument = package });
_applicationHost.NotifyPendingRestart();
}
@@ -469,7 +468,7 @@ namespace Emby.Server.Implementations.Updates
PackageVersionInfo = package
};
- EventHelper.FireEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
+ PackageInstalling?.Invoke(this, installationEventArgs);
try
{
@@ -482,7 +481,7 @@ namespace Emby.Server.Implementations.Updates
CompletedInstallationsInternal.Add(installationInfo);
- EventHelper.FireEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
+ PackageInstallationCompleted?.Invoke(this, installationEventArgs);
}
catch (OperationCanceledException)
{
@@ -491,27 +490,26 @@ namespace Emby.Server.Implementations.Updates
CurrentInstallations.Remove(tuple);
}
- _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
+ _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr);
- EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
+ PackageInstallationCancelled?.Invoke(this, installationEventArgs);
throw;
}
catch (Exception ex)
{
- _logger.ErrorException("Package installation failed", ex);
+ _logger.LogError(ex, "Package installation failed");
lock (CurrentInstallations)
{
CurrentInstallations.Remove(tuple);
}
- EventHelper.FireEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
+ PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs
{
InstallationInfo = installationInfo,
Exception = ex
-
- }, _logger);
+ });
throw;
}
@@ -549,13 +547,13 @@ namespace Emby.Server.Implementations.Updates
// Do plugin-specific processing
if (isPlugin)
{
- if (plugin != null)
+ if (plugin == null)
{
- OnPluginUpdated(plugin, package);
+ OnPluginInstalled(package);
}
else
{
- OnPluginInstalled(package);
+ OnPluginUpdated(plugin, package);
}
}
}
@@ -610,9 +608,9 @@ namespace Emby.Server.Implementations.Updates
_fileSystem.WriteAllText(target + ".ver", package.versionStr);
}
}
- catch (IOException e)
+ catch (IOException ex)
{
- _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
+ _logger.LogError(ex, "Error attempting to move file from {TempFile} to {TargetFile}", tempFile, target);
throw;
}
@@ -620,10 +618,10 @@ namespace Emby.Server.Implementations.Updates
{
_fileSystem.DeleteFile(tempFile);
}
- catch (IOException e)
+ catch (IOException ex)
{
// Don't fail because of this
- _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
+ _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile);
}
}
@@ -640,7 +638,7 @@ namespace Emby.Server.Implementations.Updates
_applicationHost.RemovePlugin(plugin);
var path = plugin.AssemblyFilePath;
- _logger.Info("Deleting plugin file {0}", path);
+ _logger.LogInformation("Deleting plugin file {0}", path);
// Make this case-insensitive to account for possible incorrect assembly naming
var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path))
diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs
index 32535b69e..d96c391fb 100644
--- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs
+++ b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs
@@ -87,7 +87,7 @@ namespace Emby.XmlTv.Classes
if (string.IsNullOrEmpty(id))
{
- //Logger.Error("No id found for channel row");
+ // LogError("No id found for channel row");
// Log.Error(" channel#{0} doesnt contain an id", iChannel);
return null;
}
@@ -130,7 +130,7 @@ namespace Emby.XmlTv.Classes
if (string.IsNullOrEmpty(result.DisplayName))
{
- //Logger.Error("No display-name found for channel {0}", id);
+ // LogError("No display-name found for channel {0}", id);
return null;
}
@@ -302,7 +302,7 @@ namespace Emby.XmlTv.Classes
var results = new Dictionary<string, int>();
//Loop through and parse out all elements and then lang= attributes
- //Logger.Info("Loading file {0}", _fileName);
+ //logger.LogInformation("Loading file {0}", _fileName);
using (var reader = CreateXmlTextReader(_fileName))
{
while (reader.Read())
@@ -1062,7 +1062,7 @@ namespace Emby.XmlTv.Classes
}
else
{
- //Logger.Warn("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate);
+ //Logger.LogWarning("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate);
}
}
@@ -1091,4 +1091,4 @@ namespace Emby.XmlTv.Classes
return String.Format("{0} {1}", dateComponent, dateOffset);
}
}
-} \ No newline at end of file
+}
diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs
new file mode 100644
index 000000000..64e03f22e
--- /dev/null
+++ b/Jellyfin.Server/CoreAppHost.cs
@@ -0,0 +1,57 @@
+using System.Collections.Generic;
+using System.Reflection;
+using Emby.Server.Implementations;
+using Emby.Server.Implementations.HttpServer;
+using Jellyfin.SocketSharp;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server
+{
+ public class CoreAppHost : ApplicationHost
+ {
+ public CoreAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager)
+ : base(applicationPaths, loggerFactory, options, fileSystem, environmentInfo, imageEncoder, systemEvents, networkManager)
+ {
+ }
+
+ public override bool CanSelfRestart
+ {
+ get
+ {
+ // A restart script must be provided
+ return StartupOptions.ContainsOption("-restartpath");
+ }
+ }
+
+ protected override void RestartInternal() => Program.Restart();
+
+ protected override IEnumerable<Assembly> GetAssembliesWithPartsInternal()
+ => new [] { typeof(CoreAppHost).Assembly };
+
+ protected override void ShutdownInternal() => Program.Shutdown();
+
+ protected override bool SupportsDualModeSockets
+ {
+ get
+ {
+ return true;
+ }
+ }
+
+ protected override IHttpListener CreateHttpListener()
+ => new WebSocketSharpListener(
+ Logger,
+ Certificate,
+ StreamHelper,
+ TextEncoding,
+ NetworkManager,
+ SocketFactory,
+ CryptographyProvider,
+ SupportsDualModeSockets,
+ FileSystemManager,
+ EnvironmentInfo
+ );
+ }
+}
diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj
new file mode 100644
index 000000000..98c578e83
--- /dev/null
+++ b/Jellyfin.Server/Jellyfin.Server.csproj
@@ -0,0 +1,44 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <AssemblyName>jellyfin</AssemblyName>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>netcoreapp2.1</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <!-- We need C# 7.1 for async main-->
+ <LangVersion>latest</LangVersion>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Include="Resources/Configuration/*" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
+ <PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
+ <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
+ <PackageReference Include="Serilog.Sinks.Async" Version="1.3.0" />
+ <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
+ <PackageReference Include="Serilog.Sinks.File" Version="4.0.0" />
+ <PackageReference Include="SkiaSharp" Version="1.68.0" />
+ <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="1.1.12" />
+ <PackageReference Include="SQLitePCLRaw.core" Version="1.1.12" />
+ <PackageReference Include="SQLitePCLRaw.provider.sqlite3.netstandard11" Version="1.1.12" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
+ <ProjectReference Include="..\Emby.Drawing.Skia\Emby.Drawing.Skia.csproj" />
+ <ProjectReference Include="..\Emby.IsoMounting\IsoMounter\IsoMounter.csproj" />
+ <ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs
new file mode 100644
index 000000000..d74315755
--- /dev/null
+++ b/Jellyfin.Server/Program.cs
@@ -0,0 +1,313 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Security;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Threading.Tasks;
+using Emby.Drawing;
+using Emby.Drawing.Skia;
+using Emby.Server.Implementations;
+using Emby.Server.Implementations.EnvironmentInfo;
+using Emby.Server.Implementations.IO;
+using Emby.Server.Implementations.Networking;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.System;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Serilog.AspNetCore;
+using ILogger = Microsoft.Extensions.Logging.ILogger;
+
+namespace Jellyfin.Server
+{
+ public static class Program
+ {
+ private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
+ private static ILoggerFactory _loggerFactory;
+ private static ILogger _logger;
+ private static bool _restartOnShutdown;
+
+ public static async Task<int> Main(string[] args)
+ {
+ StartupOptions options = new StartupOptions(args);
+ Version version = Assembly.GetEntryAssembly().GetName().Version;
+
+ if (options.ContainsOption("-v") || options.ContainsOption("--version"))
+ {
+ Console.WriteLine(version.ToString());
+ return 0;
+ }
+
+ ServerApplicationPaths appPaths = createApplicationPaths(options);
+ // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
+ Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
+ await createLogger(appPaths);
+ _loggerFactory = new SerilogLoggerFactory();
+ _logger = _loggerFactory.CreateLogger("Main");
+
+ AppDomain.CurrentDomain.UnhandledException += (sender, e)
+ => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
+
+ _logger.LogInformation("Jellyfin version: {Version}", version);
+
+ EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem());
+ ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
+
+ SQLitePCL.Batteries_V2.Init();
+
+ // Allow all https requests
+ ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
+
+ var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
+
+ using (var appHost = new CoreAppHost(
+ appPaths,
+ _loggerFactory,
+ options,
+ fileSystem,
+ environmentInfo,
+ new NullImageEncoder(),
+ new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")),
+ new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
+ {
+ appHost.Init();
+
+ appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
+
+ _logger.LogInformation("Running startup tasks");
+
+ await appHost.RunStartupTasks();
+
+ // TODO: read input for a stop command
+ // Block main thread until shutdown
+ await ApplicationTaskCompletionSource.Task;
+
+ _logger.LogInformation("Disposing app host");
+ }
+
+ if (_restartOnShutdown)
+ {
+ StartNewInstance(options);
+ }
+
+ return 0;
+ }
+
+ private static ServerApplicationPaths createApplicationPaths(StartupOptions options)
+ {
+ string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
+ if (string.IsNullOrEmpty(programDataPath))
+ {
+ if (options.ContainsOption("-programdata"))
+ {
+ programDataPath = options.GetOption("-programdata");
+ }
+ else
+ {
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
+ }
+ else
+ {
+ // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
+ programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
+ // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
+ if (string.IsNullOrEmpty(programDataPath))
+ {
+ programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
+ }
+ }
+ programDataPath = Path.Combine(programDataPath, "jellyfin");
+ // Ensure the dir exists
+ Directory.CreateDirectory(programDataPath);
+ }
+ }
+
+ string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
+ if (string.IsNullOrEmpty(configDir))
+ {
+ if (options.ContainsOption("-configdir"))
+ {
+ configDir = options.GetOption("-configdir");
+ }
+ else
+ {
+ // Let BaseApplicationPaths set up the default value
+ configDir = null;
+ }
+ }
+
+ string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
+ if (string.IsNullOrEmpty(logDir))
+ {
+ if (options.ContainsOption("-logdir"))
+ {
+ logDir = options.GetOption("-logdir");
+ }
+ else
+ {
+ // Let BaseApplicationPaths set up the default value
+ logDir = null;
+ }
+ }
+
+ string appPath = AppContext.BaseDirectory;
+
+ return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir);
+ }
+
+ private static async Task createLogger(IApplicationPaths appPaths)
+ {
+ try
+ {
+ string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
+
+ if (!File.Exists(configPath))
+ {
+ // For some reason the csproj name is used instead of the assembly name
+ using (Stream rscstr = typeof(Program).Assembly
+ .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
+ using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
+ {
+ await rscstr.CopyToAsync(fstr);
+ }
+ }
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(appPaths.ConfigurationDirectoryPath)
+ .AddJsonFile("logging.json")
+ .AddEnvironmentVariables("JELLYFIN_")
+ .Build();
+
+ // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
+ Serilog.Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .Enrich.FromLogContext()
+ .CreateLogger();
+ }
+ catch (Exception ex)
+ {
+ Serilog.Log.Logger = new LoggerConfiguration()
+ .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
+ .WriteTo.Async(x => x.File(
+ Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
+ rollingInterval: RollingInterval.Day,
+ outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
+ .Enrich.FromLogContext()
+ .CreateLogger();
+
+ Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
+ }
+ }
+
+ public static IImageEncoder getImageEncoder(
+ ILogger logger,
+ IFileSystem fileSystem,
+ StartupOptions startupOptions,
+ Func<IHttpClient> httpClient,
+ IApplicationPaths appPaths,
+ IEnvironmentInfo environment,
+ ILocalizationManager localizationManager)
+ {
+ try
+ {
+ return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
+ }
+ catch (Exception ex)
+ {
+ logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
+ }
+
+ return new NullImageEncoder();
+ }
+
+ private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
+ switch (Environment.OSVersion.Platform)
+ {
+ case PlatformID.MacOSX:
+ return MediaBrowser.Model.System.OperatingSystem.OSX;
+ case PlatformID.Win32NT:
+ return MediaBrowser.Model.System.OperatingSystem.Windows;
+ case PlatformID.Unix:
+ default:
+ {
+ string osDescription = RuntimeInformation.OSDescription;
+ if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
+ {
+ return MediaBrowser.Model.System.OperatingSystem.Linux;
+ }
+ else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
+ {
+ return MediaBrowser.Model.System.OperatingSystem.OSX;
+ }
+ else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
+ {
+ return MediaBrowser.Model.System.OperatingSystem.BSD;
+ }
+ throw new Exception($"Can't resolve OS with description: '{osDescription}'");
+ }
+ }
+ }
+
+ public static void Shutdown()
+ {
+ ApplicationTaskCompletionSource.SetResult(true);
+ }
+
+ public static void Restart()
+ {
+ _restartOnShutdown = true;
+
+ Shutdown();
+ }
+
+ private static void StartNewInstance(StartupOptions startupOptions)
+ {
+ _logger.LogInformation("Starting new instance");
+
+ string module = startupOptions.GetOption("-restartpath");
+
+ if (string.IsNullOrWhiteSpace(module))
+ {
+ module = Environment.GetCommandLineArgs().First();
+ }
+
+ string commandLineArgsString;
+
+ if (startupOptions.ContainsOption("-restartargs"))
+ {
+ commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
+ }
+ else
+ {
+ commandLineArgsString = string .Join(" ",
+ Environment.GetCommandLineArgs()
+ .Skip(1)
+ .Select(NormalizeCommandLineArgument)
+ );
+ }
+
+ _logger.LogInformation("Executable: {0}", module);
+ _logger.LogInformation("Arguments: {0}", commandLineArgsString);
+
+ Process.Start(module, commandLineArgsString);
+ }
+
+ private static string NormalizeCommandLineArgument(string arg)
+ {
+ if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
+ {
+ return arg;
+ }
+
+ return "\"" + arg + "\"";
+ }
+ }
+}
diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json
new file mode 100644
index 000000000..d16991277
--- /dev/null
+++ b/Jellyfin.Server/Resources/Configuration/logging.json
@@ -0,0 +1,28 @@
+{
+ "Serilog": {
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "Console",
+ "Args": {
+ "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}"
+ }
+ },
+ {
+ "Name": "Async",
+ "Args": {
+ "configure": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "%JELLYFIN_LOG_DIR%//log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs b/Jellyfin.Server/SocketSharp/HttpFile.cs
index 1e7c93deb..4a798062d 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs
+++ b/Jellyfin.Server/SocketSharp/HttpFile.cs
@@ -1,7 +1,7 @@
-using MediaBrowser.Model.Services;
-using System.IO;
+using System.IO;
+using MediaBrowser.Model.Services;
-namespace EmbyServer.SocketSharp
+namespace Jellyfin.SocketSharp
{
public class HttpFile : IHttpFile
{
diff --git a/MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs b/Jellyfin.Server/SocketSharp/RequestMono.cs
index 9d2354316..31f289497 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs
+++ b/Jellyfin.Server/SocketSharp/RequestMono.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
@@ -8,7 +7,7 @@ using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
-namespace EmbyServer.SocketSharp
+namespace Jellyfin.SocketSharp
{
public partial class WebSocketSharpRequest : IHttpRequest
{
@@ -52,7 +51,7 @@ namespace EmbyServer.SocketSharp
input.Position = 0;
- //Uncomment to debug
+ // Uncomment to debug
//var content = new StreamReader(ms).ReadToEnd();
//Console.WriteLine(boundary + "::" + content);
//input.Position = 0;
@@ -802,6 +801,5 @@ namespace EmbyServer.SocketSharp
return path.Substring(path.LastIndexOf('\\') + 1);
}
}
-
}
}
diff --git a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs b/Jellyfin.Server/SocketSharp/SharpWebSocket.cs
index 6c2dd0f76..77de50267 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs
+++ b/Jellyfin.Server/SocketSharp/SharpWebSocket.cs
@@ -1,12 +1,11 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Model.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Emby.Server.Implementations.Net;
+using Microsoft.Extensions.Logging;
-namespace EmbyServer.SocketSharp
+namespace Jellyfin.SocketSharp
{
public class SharpWebSocket : IWebSocket
{
@@ -55,15 +54,15 @@ namespace EmbyServer.SocketSharp
void socket_OnError(object sender, SocketHttpListener.ErrorEventArgs e)
{
- _logger.Error("Error in SharpWebSocket: {0}", e.Message ?? string.Empty);
- //EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
+ _logger.LogError("Error in SharpWebSocket: {Message}", e.Message ?? string.Empty);
+ //Closed?.Invoke(this, EventArgs.Empty);
}
void socket_OnClose(object sender, SocketHttpListener.CloseEventArgs e)
{
_taskCompletionSource.TrySetResult(true);
- EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
+ Closed?.Invoke(this, EventArgs.Empty);
}
void socket_OnMessage(object sender, SocketHttpListener.MessageEventArgs e)
diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs
index e75a38e38..c360a8fce 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs
+++ b/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs
@@ -1,23 +1,22 @@
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Model.Logging;
-using SocketHttpListener.Net;
-using System;
+using System;
using System.Collections.Generic;
-using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
+using Emby.Server.Implementations.Net;
+using Emby.Server.Implementations.HttpServer;
using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
-using Emby.Server.Implementations.Net;
-using Emby.Server.Implementations.HttpServer;
+using Microsoft.Extensions.Logging;
+using SocketHttpListener.Net;
-namespace EmbyServer.SocketSharp
+namespace Jellyfin.SocketSharp
{
public class WebSocketSharpListener : IHttpListener
{
@@ -74,7 +73,7 @@ namespace EmbyServer.SocketSharp
foreach (var prefix in urlPrefixes)
{
- _logger.Info("Adding HttpListener prefix " + prefix);
+ _logger.LogInformation("Adding HttpListener prefix " + prefix);
_listener.Prefixes.Add(prefix);
}
@@ -93,7 +92,7 @@ namespace EmbyServer.SocketSharp
{
var url = request.Url.ToString();
- logger.Info("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty);
+ logger.LogInformation("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty);
}
private Task InitTask(HttpListenerContext context, CancellationToken cancellationToken)
@@ -114,7 +113,7 @@ namespace EmbyServer.SocketSharp
}
catch (Exception ex)
{
- _logger.ErrorException("Error processing request", ex);
+ _logger.LogError(ex, "Error processing request");
httpReq = httpReq ?? GetRequest(context);
return ErrorHandler(ex, httpReq, true, true);
@@ -148,7 +147,7 @@ namespace EmbyServer.SocketSharp
if (connectingArgs.AllowConnection)
{
- _logger.Debug("Web socket connection allowed");
+ _logger.LogDebug("Web socket connection allowed");
var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
@@ -169,14 +168,14 @@ namespace EmbyServer.SocketSharp
}
else
{
- _logger.Warn("Web socket connection not allowed");
+ _logger.LogWarning("Web socket connection not allowed");
ctx.Response.StatusCode = 401;
ctx.Response.Close();
}
}
catch (Exception ex)
{
- _logger.ErrorException("AcceptWebSocketAsync error", ex);
+ _logger.LogError(ex, "AcceptWebSocketAsync error");
ctx.Response.StatusCode = 500;
ctx.Response.Close();
}
@@ -206,7 +205,7 @@ namespace EmbyServer.SocketSharp
}
catch (Exception ex)
{
- _logger.ErrorException("Error closing web socket response", ex);
+ _logger.LogError(ex, "Error closing web socket response");
}
}
@@ -258,5 +257,4 @@ namespace EmbyServer.SocketSharp
}
}
}
-
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs
index 84e37a58c..7c9dc8f88 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs
+++ b/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs
@@ -3,17 +3,15 @@ using System.Collections.Generic;
using System.IO;
using System.Text;
using Emby.Server.Implementations.HttpServer;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
using SocketHttpListener.Net;
using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
using IResponse = MediaBrowser.Model.Services.IResponse;
-using System.Threading.Tasks;
-namespace EmbyServer.SocketSharp
+namespace Jellyfin.SocketSharp
{
public partial class WebSocketSharpRequest : IHttpRequest
{
diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs
index 15ff6675d..c7437c825 100644
--- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs
+++ b/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs
@@ -2,18 +2,19 @@
using System.Collections.Generic;
using System.IO;
using System.Net;
+using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse;
using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
using IRequest = MediaBrowser.Model.Services.IRequest;
-using System.Net.Sockets;
-namespace EmbyServer.SocketSharp
+
+namespace Jellyfin.SocketSharp
{
public class WebSocketSharpResponse : IHttpResponse
{
@@ -112,7 +113,7 @@ namespace EmbyServer.SocketSharp
}
catch (Exception ex)
{
- _logger.ErrorException("Error in HttpListenerResponseWrapper: " + ex.Message, ex);
+ _logger.LogError(ex, "Error in HttpListenerResponseWrapper");
}
}
}
diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs
index 5aa803b9b..ed0a0c81a 100644
--- a/MediaBrowser.Api/ApiEntryPoint.cs
+++ b/MediaBrowser.Api/ApiEntryPoint.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Threading;
using System.Collections.Generic;
using System.Threading;
@@ -147,7 +147,7 @@ namespace MediaBrowser.Api
}
catch (Exception ex)
{
- Logger.ErrorException("Error deleting encoded media cache", ex);
+ Logger.LogError(ex, "Error deleting encoded media cache");
}
}
@@ -378,7 +378,7 @@ namespace MediaBrowser.Api
public void OnTranscodeEndRequest(TranscodingJob job)
{
job.ActiveRequestCount--;
- //Logger.Debug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
+ //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
if (job.ActiveRequestCount <= 0)
{
PingTimer(job, false);
@@ -391,7 +391,7 @@ namespace MediaBrowser.Api
throw new ArgumentNullException("playSessionId");
}
- //Logger.Debug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
+ //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
List<TranscodingJob> jobs;
@@ -406,7 +406,7 @@ namespace MediaBrowser.Api
{
if (isUserPaused.HasValue)
{
- //Logger.Debug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
+ //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
job.IsUserPaused = isUserPaused.Value;
}
PingTimer(job, true);
@@ -461,7 +461,7 @@ namespace MediaBrowser.Api
}
}
- Logger.Info("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+ Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
KillTranscodingJob(job, true, path => true);
}
@@ -525,7 +525,7 @@ namespace MediaBrowser.Api
{
job.DisposeKillTimer();
- Logger.Debug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+ Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
lock (_activeTranscodingJobs)
{
@@ -557,7 +557,7 @@ namespace MediaBrowser.Api
{
try
{
- Logger.Info("Stopping ffmpeg process with q command for {0}", job.Path);
+ Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path);
//process.Kill();
process.StandardInput.WriteLine("q");
@@ -565,13 +565,13 @@ namespace MediaBrowser.Api
// Need to wait because killing is asynchronous
if (!process.WaitForExit(5000))
{
- Logger.Info("Killing ffmpeg process for {0}", job.Path);
+ Logger.LogInformation("Killing ffmpeg process for {path}", job.Path);
process.Kill();
}
}
catch (Exception ex)
{
- Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
+ Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path);
}
}
}
@@ -589,7 +589,7 @@ namespace MediaBrowser.Api
}
catch (Exception ex)
{
- Logger.ErrorException("Error closing live stream for {0}", ex, job.Path);
+ Logger.LogError(ex, "Error closing live stream for {path}", job.Path);
}
}
}
@@ -601,7 +601,7 @@ namespace MediaBrowser.Api
return;
}
- Logger.Info("Deleting partial stream file(s) {0}", path);
+ Logger.LogInformation("Deleting partial stream file(s) {0}", path);
await Task.Delay(delayMs).ConfigureAwait(false);
@@ -620,15 +620,15 @@ namespace MediaBrowser.Api
{
}
- catch (IOException)
+ catch (IOException ex)
{
- //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
+ Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
}
- catch
+ catch (Exception ex)
{
- //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
+ Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
}
}
@@ -660,7 +660,7 @@ namespace MediaBrowser.Api
{
try
{
- //Logger.Debug("Deleting HLS file {0}", file);
+ //Logger.LogDebug("Deleting HLS file {0}", file);
_fileSystem.DeleteFile(file);
}
catch (FileNotFoundException)
@@ -670,7 +670,7 @@ namespace MediaBrowser.Api
catch (IOException ex)
{
e = ex;
- //Logger.ErrorException("Error deleting HLS file {0}", ex, file);
+ Logger.LogError(ex, "Error deleting HLS file {path}", file);
}
}
@@ -802,12 +802,12 @@ namespace MediaBrowser.Api
{
if (KillTimer == null)
{
- //Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer = _timerFactory.Create(callback, this, intervalMs, Timeout.Infinite);
}
else
{
- //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer.Change(intervalMs, Timeout.Infinite);
}
}
@@ -826,7 +826,7 @@ namespace MediaBrowser.Api
{
var intervalMs = PingTimeout;
- //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer.Change(intervalMs, Timeout.Infinite);
}
}
diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs
index e243927a0..ed31cbd1d 100644
--- a/MediaBrowser.Api/BaseApiService.cs
+++ b/MediaBrowser.Api/BaseApiService.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -55,12 +55,11 @@ namespace MediaBrowser.Api
return Request.Headers[name];
}
- private static readonly string[] EmptyStringArray = Array.Empty<string>();
public static string[] SplitValue(string value, char delim)
{
if (string.IsNullOrWhiteSpace(value))
{
- return EmptyStringArray;
+ return Array.Empty<string>();
}
return value.Split(new[] { delim }, StringSplitOptions.RemoveEmptyEntries);
diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs
index c3b2e82e7..17c6d5dc5 100644
--- a/MediaBrowser.Api/Images/ImageService.cs
+++ b/MediaBrowser.Api/Images/ImageService.cs
@@ -21,6 +21,8 @@ using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
+
namespace MediaBrowser.Api.Images
{
/// <summary>
@@ -360,7 +362,7 @@ namespace MediaBrowser.Api.Images
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting image information for {0}", ex, info.Path);
+ Logger.LogError(ex, "Error getting image information for {path}", info.Path);
return null;
}
@@ -673,7 +675,7 @@ namespace MediaBrowser.Api.Images
private ImageFormat[] GetClientSupportedFormats()
{
- //Logger.Debug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty<string>()));
+ //logger.LogDebug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty<string>()));
var supportedFormats = (Request.AcceptTypes ?? Array.Empty<string>()).Select(i => i.Split(';')[0]).ToArray();
var acceptParam = Request.QueryString["accept"];
diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs
index 39a790486..331fb711d 100644
--- a/MediaBrowser.Api/ItemLookupService.cs
+++ b/MediaBrowser.Api/ItemLookupService.cs
@@ -17,6 +17,7 @@ using System.Threading.Tasks;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api
{
@@ -232,14 +233,14 @@ namespace MediaBrowser.Api
// item.SetProviderId(key.Key, value);
// }
//}
- Logger.Info("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds));
+ Logger.LogInformation("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds));
// Since the refresh process won't erase provider Ids, we need to set this explicitly now.
item.ProviderIds = request.ProviderIds;
//item.ProductionYear = request.ProductionYear;
//item.Name = request.Name;
- return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(_fileSystem)
+ return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
{
MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
ImageRefreshMode = MetadataRefreshMode.FullRefresh,
diff --git a/MediaBrowser.Api/ItemRefreshService.cs b/MediaBrowser.Api/ItemRefreshService.cs
index ab083c207..ba1c809fe 100644
--- a/MediaBrowser.Api/ItemRefreshService.cs
+++ b/MediaBrowser.Api/ItemRefreshService.cs
@@ -6,7 +6,7 @@ using System.Threading;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Services;
namespace MediaBrowser.Api
diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs
index 22eb7ea09..d89750eae 100644
--- a/MediaBrowser.Api/ItemUpdateService.cs
+++ b/MediaBrowser.Api/ItemUpdateService.cs
@@ -230,7 +230,7 @@ namespace MediaBrowser.Api
if (displayOrderChanged)
{
- _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(_fileSystem)
+ _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
{
MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
ImageRefreshMode = MetadataRefreshMode.FullRefresh,
diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs
index cc8c1251f..ecf3eb7db 100644
--- a/MediaBrowser.Api/Library/LibraryService.cs
+++ b/MediaBrowser.Api/Library/LibraryService.cs
@@ -32,6 +32,7 @@ using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Library
{
@@ -1000,7 +1001,7 @@ namespace MediaBrowser.Api.Library
}
catch (Exception ex)
{
- Logger.ErrorException("Error refreshing library", ex);
+ Logger.LogError(ex, "Error refreshing library");
}
});
}
diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs
index 06c0c6862..ef9ce9aec 100644
--- a/MediaBrowser.Api/LiveTv/LiveTvService.cs
+++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs
@@ -17,7 +17,6 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Api.UserLibrary;
using MediaBrowser.Model.IO;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Model.Services;
diff --git a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs
index 0a6ccd4c5..07ac7f28d 100644
--- a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs
+++ b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs
@@ -5,10 +5,10 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
using MediaBrowser.Controller.IO;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.LiveTv
{
@@ -95,7 +95,7 @@ namespace MediaBrowser.Api.LiveTv
bytesRead = await _streamHelper.CopyToAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
//var position = fs.Position;
- //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
+ //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
if (bytesRead == 0)
{
diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj
index 3fa60fad1..5ffaaed27 100644
--- a/MediaBrowser.Api/MediaBrowser.Api.csproj
+++ b/MediaBrowser.Api/MediaBrowser.Api.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/MediaBrowser.Api/NewsService.cs b/MediaBrowser.Api/NewsService.cs
deleted file mode 100644
index cbc77bfc9..000000000
--- a/MediaBrowser.Api/NewsService.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using MediaBrowser.Model.News;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-
-namespace MediaBrowser.Api
-{
- [Route("/News/Product", "GET", Summary = "Gets the latest product news.")]
- public class GetProductNews : IReturn<QueryResult<NewsItem>>
- {
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- /// <value>The start index.</value>
- [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? StartIndex { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
- public int? Limit { get; set; }
- }
-
- public class NewsService : BaseApiService
- {
- private readonly INewsService _newsService;
-
- public NewsService(INewsService newsService)
- {
- _newsService = newsService;
- }
-
- public object Get(GetProductNews request)
- {
- var result = _newsService.GetProductNews(new NewsQuery
- {
- StartIndex = request.StartIndex,
- Limit = request.Limit
-
- });
-
- return ToOptimizedResult(result);
- }
- }
-}
diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs
index 9c2e0e9d8..fa6502bda 100644
--- a/MediaBrowser.Api/Playback/BaseStreamingService.cs
+++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs
@@ -24,6 +24,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Diagnostics;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback
{
@@ -248,7 +249,7 @@ namespace MediaBrowser.Api.Playback
cancellationTokenSource);
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
- Logger.Info(commandLineLogMessage);
+ Logger.LogInformation(commandLineLogMessage);
var logFilePrefix = "ffmpeg-transcode";
if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
@@ -277,7 +278,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- Logger.ErrorException("Error starting ffmpeg", ex);
+ Logger.LogError(ex, "Error starting ffmpeg");
ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
@@ -351,16 +352,16 @@ namespace MediaBrowser.Api.Playback
job.HasExited = true;
}
- Logger.Debug("Disposing stream resources");
+ Logger.LogDebug("Disposing stream resources");
state.Dispose();
try
{
- Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
+ Logger.LogInformation("FFMpeg exited with code {0}", process.ExitCode);
}
catch
{
- Logger.Error("FFMpeg exited with an error.");
+ Logger.LogError("FFMpeg exited with an error.");
}
// This causes on exited to be called twice:
@@ -371,7 +372,7 @@ namespace MediaBrowser.Api.Playback
//}
//catch (Exception ex)
//{
- // Logger.ErrorException("Error disposing ffmpeg.", ex);
+ // Logger.LogError(ex, "Error disposing ffmpeg.");
//}
}
@@ -589,6 +590,22 @@ namespace MediaBrowser.Api.Playback
}
/// <summary>
+ /// Parses query parameters as StreamOptions
+ /// <summary>
+ /// <param name="request">The stream request.</param>
+ private void ParseStreamOptions(StreamRequest request)
+ {
+ foreach (var param in Request.QueryString) {
+ if (Char.IsLower(param.Name[0])) {
+ // This was probably not parsed initially and should be a StreamOptions
+ // TODO: This should be incorporated either in the lower framework for parsing requests
+ // or the generated URL should correctly serialize it
+ request.StreamOptions[param.Name] = param.Value;
+ }
+ }
+ }
+
+ /// <summary>
/// Parses the dlna headers.
/// </summary>
/// <param name="request">The request.</param>
@@ -666,6 +683,8 @@ namespace MediaBrowser.Api.Playback
ParseParams(request);
}
+ ParseStreamOptions(request);
+
var url = Request.PathInfo;
if (string.IsNullOrEmpty(request.AudioCodec))
@@ -685,7 +704,7 @@ namespace MediaBrowser.Api.Playback
};
var auth = AuthorizationContext.GetAuthorizationInfo(Request);
- if (auth.UserId != null)
+ if (!auth.UserId.Equals(Guid.Empty))
{
state.User = UserManager.GetUserById(auth.UserId);
}
diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
index a0f4a2e71..7ef7b81e6 100644
--- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
+++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
@@ -15,6 +15,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Configuration;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback.Hls
{
@@ -185,7 +186,7 @@ namespace MediaBrowser.Api.Playback.Hls
protected virtual async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
{
- Logger.Debug("Waiting for {0} segments in {1}", segmentCount, playlist);
+ Logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist);
while (!cancellationToken.IsCancellationRequested)
{
@@ -207,7 +208,7 @@ namespace MediaBrowser.Api.Playback.Hls
count++;
if (count >= segmentCount)
{
- Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
+ Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
return;
}
}
@@ -330,4 +331,4 @@ namespace MediaBrowser.Api.Playback.Hls
{
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
index 0525c8cc4..5361e313c 100644
--- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
+++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
@@ -21,6 +21,7 @@ using System.Threading.Tasks;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Services;
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback.Hls
{
@@ -190,17 +191,17 @@ namespace MediaBrowser.Api.Playback.Hls
if (currentTranscodingIndex == null)
{
- Logger.Debug("Starting transcoding because currentTranscodingIndex=null");
+ Logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
startTranscoding = true;
}
else if (requestedIndex < currentTranscodingIndex.Value)
{
- Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
+ Logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
startTranscoding = true;
}
else if (requestedIndex - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
{
- Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex);
+ Logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex);
startTranscoding = true;
}
if (startTranscoding)
@@ -245,13 +246,13 @@ namespace MediaBrowser.Api.Playback.Hls
}
}
- //Logger.Info("waiting for {0}", segmentPath);
+ //Logger.LogInformation("waiting for {0}", segmentPath);
//while (!File.Exists(segmentPath))
//{
// await Task.Delay(50, cancellationToken).ConfigureAwait(false);
//}
- Logger.Info("returning {0}", segmentPath);
+ Logger.LogInformation("returning {0}", segmentPath);
job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false);
}
@@ -358,7 +359,7 @@ namespace MediaBrowser.Api.Playback.Hls
return;
}
- Logger.Debug("Deleting partial HLS file {0}", path);
+ Logger.LogDebug("Deleting partial HLS file {path}", path);
try
{
@@ -366,7 +367,7 @@ namespace MediaBrowser.Api.Playback.Hls
}
catch (IOException ex)
{
- Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
+ Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
var task = Task.Delay(100);
Task.WaitAll(task);
@@ -374,7 +375,7 @@ namespace MediaBrowser.Api.Playback.Hls
}
catch (Exception ex)
{
- Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
+ Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
}
}
@@ -968,4 +969,4 @@ namespace MediaBrowser.Api.Playback.Hls
).Trim();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs
index 2db0f8f41..6dafe134c 100644
--- a/MediaBrowser.Api/Playback/MediaInfoService.cs
+++ b/MediaBrowser.Api/Playback/MediaInfoService.cs
@@ -18,6 +18,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback
{
@@ -381,11 +382,11 @@ namespace MediaBrowser.Api.Playback
if (item is Audio)
{
- Logger.Info("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding);
+ Logger.LogInformation("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding);
}
else
{
- Logger.Info("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}",
+ Logger.LogInformation("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}",
user.Name,
user.Policy.EnablePlaybackRemuxing,
user.Policy.EnableVideoPlaybackTranscoding,
@@ -525,7 +526,7 @@ namespace MediaBrowser.Api.Playback
{
var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp);
- Logger.Info("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
+ Logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
if (!isInLocalNetwork)
{
maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
index 44261f2d5..cc59b1049 100644
--- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
+++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
@@ -17,6 +17,8 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
+using MediaBrowser.Api.LiveTv;
namespace MediaBrowser.Api.Playback.Progressive
{
diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
index 9839a7a9a..ed2930b4d 100644
--- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
+++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
@@ -1,16 +1,15 @@
-using MediaBrowser.Model.Logging;
-using System;
+using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
using MediaBrowser.Controller.Net;
using System.Collections.Generic;
-
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback.Progressive
{
@@ -110,7 +109,7 @@ namespace MediaBrowser.Api.Playback.Progressive
}
//var position = fs.Position;
- //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
+ //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
if (bytesRead == 0)
{
diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs
index db5d256c4..67fb04d0c 100644
--- a/MediaBrowser.Api/Playback/StreamState.cs
+++ b/MediaBrowser.Api/Playback/StreamState.cs
@@ -4,7 +4,6 @@ using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
using System;
@@ -14,6 +13,7 @@ using System.IO;
using System.Linq;
using System.Threading;
using MediaBrowser.Controller.MediaEncoding;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback
{
@@ -162,7 +162,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing log stream", ex);
+ _logger.LogError(ex, "Error disposing log stream");
}
LogFileStream = null;
@@ -179,7 +179,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing TranscodingThrottler", ex);
+ _logger.LogError(ex, "Error disposing TranscodingThrottler");
}
TranscodingThrottler = null;
@@ -196,7 +196,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- _logger.ErrorException("Error closing media source", ex);
+ _logger.LogError(ex, "Error closing media source");
}
}
}
diff --git a/MediaBrowser.Api/Playback/TranscodingThrottler.cs b/MediaBrowser.Api/Playback/TranscodingThrottler.cs
index c42d0c3e4..5852852f6 100644
--- a/MediaBrowser.Api/Playback/TranscodingThrottler.cs
+++ b/MediaBrowser.Api/Playback/TranscodingThrottler.cs
@@ -1,9 +1,9 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Logging;
using System;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Threading;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Playback
{
@@ -60,7 +60,7 @@ namespace MediaBrowser.Api.Playback
{
if (!_isPaused)
{
- _logger.Debug("Sending pause command to ffmpeg");
+ _logger.LogDebug("Sending pause command to ffmpeg");
try
{
@@ -69,7 +69,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- _logger.ErrorException("Error pausing transcoding", ex);
+ _logger.LogError(ex, "Error pausing transcoding");
}
}
}
@@ -78,7 +78,7 @@ namespace MediaBrowser.Api.Playback
{
if (_isPaused)
{
- _logger.Debug("Sending unpause command to ffmpeg");
+ _logger.LogDebug("Sending resume command to ffmpeg");
try
{
@@ -87,7 +87,7 @@ namespace MediaBrowser.Api.Playback
}
catch (Exception ex)
{
- _logger.ErrorException("Error unpausing transcoding", ex);
+ _logger.LogError(ex, "Error resuming transcoding");
}
}
}
@@ -110,11 +110,11 @@ namespace MediaBrowser.Api.Playback
if (gap < targetGap)
{
- //_logger.Debug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
+ _logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
return false;
}
- //_logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
+ _logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
return true;
}
@@ -135,21 +135,21 @@ namespace MediaBrowser.Api.Playback
if (gap < targetGap)
{
- //_logger.Debug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
+ _logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
return false;
}
- //_logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
+ _logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
return true;
}
- catch
+ catch (Exception ex)
{
- //_logger.Error("Error getting output size");
+ _logger.LogError(ex, "Error getting output size");
return false;
}
}
- //_logger.Debug("No throttle data for " + path);
+ _logger.LogDebug("No throttle data for " + path);
return false;
}
diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs
index 1ee096a2e..1f1bb3614 100644
--- a/MediaBrowser.Api/PluginService.cs
+++ b/MediaBrowser.Api/PluginService.cs
@@ -8,13 +8,13 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
using System;
-using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using MediaBrowser.Common.Plugins;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api
{
@@ -230,9 +230,9 @@ namespace MediaBrowser.Api
.ToArray();
}
}
- catch
+ catch (Exception ex)
{
- //Logger.ErrorException("Error getting plugin list", ex);
+ Logger.LogError(ex, "Error getting plugin list");
// Play it safe here
if (requireAppStoreEnabled)
{
diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs
index ff57b4dd1..fa5fa99d1 100644
--- a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs
+++ b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Tasks;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs
index ca2c381cf..533e7d307 100644
--- a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs
+++ b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Session;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Api/SimilarItemsHelper.cs b/MediaBrowser.Api/SimilarItemsHelper.cs
index db5908f76..db075e8f4 100644
--- a/MediaBrowser.Api/SimilarItemsHelper.cs
+++ b/MediaBrowser.Api/SimilarItemsHelper.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs
index 7fccbcc9b..0ddc1e1dd 100644
--- a/MediaBrowser.Api/StartupWizardService.cs
+++ b/MediaBrowser.Api/StartupWizardService.cs
@@ -68,35 +68,6 @@ namespace MediaBrowser.Api
_config.Configuration.IsStartupWizardCompleted = true;
_config.SetOptimalValues();
_config.SaveConfiguration();
-
- Task.Run(UpdateStats);
- }
-
- private async Task UpdateStats()
- {
- try
- {
- var url = string.Format("http://www.mb3admin.local/admin/service/package/installed?mac={0}&product=MBServer&operation=Install&version={1}",
- _appHost.SystemId,
- _appHost.ApplicationVersion.ToString());
-
- using (var response = await _httpClient.SendAsync(new HttpRequestOptions
- {
-
- Url = url,
- CancellationToken = CancellationToken.None,
- LogErrors = false,
- LogRequest = false
-
- }, "GET").ConfigureAwait(false))
- {
-
- }
- }
- catch
- {
-
- }
}
public object Get(GetStartupConfiguration request)
diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs
index c8b0a32e9..0e5b0a964 100644
--- a/MediaBrowser.Api/Subtitles/SubtitleService.cs
+++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs
@@ -17,6 +17,7 @@ using System.Threading.Tasks;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.Subtitles
{
@@ -273,11 +274,11 @@ namespace MediaBrowser.Api.Subtitles
await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None)
.ConfigureAwait(false);
- _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High);
+ _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High);
}
catch (Exception ex)
{
- Logger.ErrorException("Error downloading subtitles", ex);
+ Logger.LogError(ex, "Error downloading subtitles");
}
});
diff --git a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs
index 6991244c6..b61ff8d93 100644
--- a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs
+++ b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs
index d2880f735..52e14dbcc 100644
--- a/MediaBrowser.Api/System/SystemService.cs
+++ b/MediaBrowser.Api/System/SystemService.cs
@@ -9,12 +9,11 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
-
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Services;
using System.Threading;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.System
{
@@ -137,11 +136,12 @@ namespace MediaBrowser.Api.System
try
{
- files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt" }, true, false);
+ files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt", ".log" }, true, false);
}
- catch (IOException)
+ catch (IOException ex)
{
- files = new FileSystemMetadata[] { };
+ Logger.LogError(ex, "Error getting logs");
+ files = Enumerable.Empty<FileSystemMetadata>();
}
var result = files.Select(i => new LogFile
diff --git a/MediaBrowser.Api/UserLibrary/PlaystateService.cs b/MediaBrowser.Api/UserLibrary/PlaystateService.cs
index 2c514a109..9b269542a 100644
--- a/MediaBrowser.Api/UserLibrary/PlaystateService.cs
+++ b/MediaBrowser.Api/UserLibrary/PlaystateService.cs
@@ -6,9 +6,9 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Session;
using System;
using System.Globalization;
-using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api.UserLibrary
{
@@ -381,7 +381,7 @@ namespace MediaBrowser.Api.UserLibrary
public void Post(ReportPlaybackStopped request)
{
- Logger.Debug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty);
+ Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty);
if (!string.IsNullOrWhiteSpace(request.PlaySessionId))
{
diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs
index 30df0ad23..d188d7f7e 100644
--- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs
+++ b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs
@@ -404,7 +404,7 @@ namespace MediaBrowser.Api.UserLibrary
if (!hasMetdata)
{
- var options = new MetadataRefreshOptions(_fileSystem)
+ var options = new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem))
{
MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
ImageRefreshMode = MetadataRefreshMode.FullRefresh,
diff --git a/MediaBrowser.Api/UserService.cs b/MediaBrowser.Api/UserService.cs
index 29f3070a5..913a55b2b 100644
--- a/MediaBrowser.Api/UserService.cs
+++ b/MediaBrowser.Api/UserService.cs
@@ -1,4 +1,5 @@
-using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
@@ -10,11 +11,9 @@ using MediaBrowser.Model.Connect;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Users;
using System;
-using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
-using MediaBrowser.Controller.Authentication;
namespace MediaBrowser.Api
{
diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs
index 2bb52f0ae..2630ce7da 100644
--- a/MediaBrowser.Common/Events/EventHelper.cs
+++ b/MediaBrowser.Common/Events/EventHelper.cs
@@ -1,9 +1,10 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Events
{
+ // TODO: @bond Remove
/// <summary>
/// Class EventHelper
/// </summary>
@@ -28,7 +29,7 @@ namespace MediaBrowser.Common.Events
}
catch (Exception ex)
{
- logger.ErrorException("Error in event handler", ex);
+ logger.LogError(ex, "Error in event handler");
}
});
}
@@ -54,55 +55,10 @@ namespace MediaBrowser.Common.Events
}
catch (Exception ex)
{
- logger.ErrorException("Error in event handler", ex);
+ logger.LogError(ex, "Error in event handler");
}
});
}
}
-
- /// <summary>
- /// Fires the event.
- /// </summary>
- /// <param name="handler">The handler.</param>
- /// <param name="sender">The sender.</param>
- /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param>
- /// <param name="logger">The logger.</param>
- public static void FireEventIfNotNull(EventHandler handler, object sender, EventArgs args, ILogger logger)
- {
- if (handler != null)
- {
- try
- {
- handler(sender, args);
- }
- catch (Exception ex)
- {
- logger.ErrorException("Error in event handler", ex);
- }
- }
- }
-
- /// <summary>
- /// Fires the event.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="handler">The handler.</param>
- /// <param name="sender">The sender.</param>
- /// <param name="args">The args.</param>
- /// <param name="logger">The logger.</param>
- public static void FireEventIfNotNull<T>(EventHandler<T> handler, object sender, T args, ILogger logger)
- {
- if (handler != null)
- {
- try
- {
- handler(sender, args);
- }
- catch (Exception ex)
- {
- logger.ErrorException("Error in event handler", ex);
- }
- }
- }
}
}
diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs
index d7f4424fa..520c04244 100644
--- a/MediaBrowser.Common/Extensions/BaseExtensions.cs
+++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs
@@ -34,25 +34,5 @@ namespace MediaBrowser.Common.Extensions
{
return CryptographyProvider.GetMD5(str);
}
-
- /// <summary>
- /// Gets the MB id.
- /// </summary>
- /// <param name="str">The STR.</param>
- /// <param name="type">The type.</param>
- /// <returns>Guid.</returns>
- /// <exception cref="System.ArgumentNullException">type</exception>
- [Obsolete("Use LibraryManager.GetNewItemId")]
- public static Guid GetMBId(this string str, Type type)
- {
- if (type == null)
- {
- throw new ArgumentNullException("type");
- }
-
- var key = type.FullName + str.ToLower();
-
- return key.GetMD5();
- }
}
}
diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs
index 32b942b60..c4f760b15 100644
--- a/MediaBrowser.Common/IApplicationHost.cs
+++ b/MediaBrowser.Common/IApplicationHost.cs
@@ -86,12 +86,6 @@ namespace MediaBrowser.Common
IEnumerable<T> GetExports<T>(bool manageLiftime = true);
/// <summary>
- /// Checks for update.
- /// </summary>
- /// <returns>Task{CheckForUpdateResult}.</returns>
- Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress);
-
- /// <summary>
/// Updates the application.
/// </summary>
/// <returns>Task.</returns>
@@ -141,7 +135,5 @@ namespace MediaBrowser.Common
object CreateInstance(Type type);
PackageVersionClass SystemUpdateLevel { get; }
-
- string GetValue(string name);
}
}
diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj
index 43f3b0be7..f625a17ee 100644
--- a/MediaBrowser.Common/MediaBrowser.Common.csproj
+++ b/MediaBrowser.Common/MediaBrowser.Common.csproj
@@ -5,7 +5,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/MediaBrowser.Common/Net/IHttpClient.cs b/MediaBrowser.Common/Net/IHttpClient.cs
index cf5511965..f88cfbb2b 100644
--- a/MediaBrowser.Common/Net/IHttpClient.cs
+++ b/MediaBrowser.Common/Net/IHttpClient.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
+using System.IO;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Net
@@ -56,4 +53,4 @@ namespace MediaBrowser.Common.Net
/// <returns>Task{HttpResponseInfo}.</returns>
Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options);
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Common/Updates/GithubUpdater.cs b/MediaBrowser.Common/Updates/GithubUpdater.cs
deleted file mode 100644
index 4275799a9..000000000
--- a/MediaBrowser.Common/Updates/GithubUpdater.cs
+++ /dev/null
@@ -1,278 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Updates;
-
-namespace MediaBrowser.Common.Updates
-{
- public class GithubUpdater
- {
- private readonly IHttpClient _httpClient;
- private readonly IJsonSerializer _jsonSerializer;
-
- public GithubUpdater(IHttpClient httpClient, IJsonSerializer jsonSerializer)
- {
- _httpClient = httpClient;
- _jsonSerializer = jsonSerializer;
- }
-
- public async Task<CheckForUpdateResult> CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, TimeSpan cacheLength, CancellationToken cancellationToken)
- {
- var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository);
-
- var options = new HttpRequestOptions
- {
- Url = url,
- EnableKeepAlive = false,
- CancellationToken = cancellationToken,
- UserAgent = "Emby/3.0",
- BufferContent = false
- };
-
- if (cacheLength.Ticks > 0)
- {
- options.CacheMode = CacheMode.Unconditional;
- options.CacheLength = cacheLength;
- }
-
- using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- var obj = _jsonSerializer.DeserializeFromStream<RootObject[]>(stream);
-
- return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename);
- }
- }
- }
-
- private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename)
- {
- if (updateLevel == PackageVersionClass.Release)
- {
- // Technically all we need to do is check that it's not pre-release
- // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly.
- obj = obj.Where(i => !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) && !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray();
- }
- else if (updateLevel == PackageVersionClass.Beta)
- {
- obj = obj.Where(i => i.prerelease && i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase)).ToArray();
- }
- else if (updateLevel == PackageVersionClass.Dev)
- {
- obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray();
- }
-
- var availableUpdate = obj
- .Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename))
- .Where(i => i != null)
- .OrderByDescending(i => Version.Parse(i.AvailableVersion))
- .FirstOrDefault();
-
- return availableUpdate ?? new CheckForUpdateResult
- {
- IsUpdateAvailable = false
- };
- }
-
- private bool MatchesUpdateLevel(RootObject i, PackageVersionClass updateLevel)
- {
- if (updateLevel == PackageVersionClass.Beta)
- {
- return i.prerelease && i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase);
- }
- if (updateLevel == PackageVersionClass.Dev)
- {
- return !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) ||
- i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase);
- }
-
- // Technically all we need to do is check that it's not pre-release
- // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly.
- return !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) &&
- !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase);
- }
-
- public async Task<List<RootObject>> GetLatestReleases(string organzation, string repository, string assetFilename, CancellationToken cancellationToken)
- {
- var list = new List<RootObject>();
-
- var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository);
-
- var options = new HttpRequestOptions
- {
- Url = url,
- EnableKeepAlive = false,
- CancellationToken = cancellationToken,
- UserAgent = "Emby/3.0",
- BufferContent = false
- };
-
- using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- var obj = _jsonSerializer.DeserializeFromStream<RootObject[]>(stream);
-
- obj = obj.Where(i => (i.assets ?? new List<Asset>()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray();
-
- list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1));
- list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1));
- list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1));
-
- return list;
- }
- }
- }
-
- public Version GetVersion(RootObject obj)
- {
- Version version;
- if (!Version.TryParse(obj.tag_name, out version))
- {
- return new Version(1, 0);
- }
-
- return version;
- }
-
- private CheckForUpdateResult CheckForUpdateResult(RootObject obj, Version minVersion, string assetFilename, string packageName, string targetFilename)
- {
- Version version;
- var versionString = obj.tag_name;
- if (!Version.TryParse(versionString, out version))
- {
- return null;
- }
-
- if (version < minVersion)
- {
- return null;
- }
-
- var asset = (obj.assets ?? new List<Asset>()).FirstOrDefault(i => IsAsset(i, assetFilename, versionString));
-
- if (asset == null)
- {
- return null;
- }
-
- return new CheckForUpdateResult
- {
- AvailableVersion = version.ToString(),
- IsUpdateAvailable = version > minVersion,
- Package = new PackageVersionInfo
- {
- classification = obj.prerelease ?
- (obj.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase) ? PackageVersionClass.Dev : PackageVersionClass.Beta) :
- PackageVersionClass.Release,
- name = packageName,
- sourceUrl = asset.browser_download_url,
- targetFilename = targetFilename,
- versionStr = version.ToString(),
- requiredVersionStr = "1.0.0",
- description = obj.body,
- infoUrl = obj.html_url
- }
- };
- }
-
- private bool IsAsset(Asset asset, string assetFilename, string version)
- {
- var downloadFilename = Path.GetFileName(asset.browser_download_url) ?? string.Empty;
-
- assetFilename = assetFilename.Replace("{version}", version);
-
- if (downloadFilename.IndexOf(assetFilename, StringComparison.OrdinalIgnoreCase) != -1)
- {
- return true;
- }
-
- return string.Equals(assetFilename, downloadFilename, StringComparison.OrdinalIgnoreCase);
- }
-
- public class Uploader
- {
- public string login { get; set; }
- public int id { get; set; }
- public string avatar_url { get; set; }
- public string gravatar_id { get; set; }
- public string url { get; set; }
- public string html_url { get; set; }
- public string followers_url { get; set; }
- public string following_url { get; set; }
- public string gists_url { get; set; }
- public string starred_url { get; set; }
- public string subscriptions_url { get; set; }
- public string organizations_url { get; set; }
- public string repos_url { get; set; }
- public string events_url { get; set; }
- public string received_events_url { get; set; }
- public string type { get; set; }
- public bool site_admin { get; set; }
- }
-
- public class Asset
- {
- public string url { get; set; }
- public int id { get; set; }
- public string name { get; set; }
- public object label { get; set; }
- public Uploader uploader { get; set; }
- public string content_type { get; set; }
- public string state { get; set; }
- public int size { get; set; }
- public int download_count { get; set; }
- public string created_at { get; set; }
- public string updated_at { get; set; }
- public string browser_download_url { get; set; }
- }
-
- public class Author
- {
- public string login { get; set; }
- public int id { get; set; }
- public string avatar_url { get; set; }
- public string gravatar_id { get; set; }
- public string url { get; set; }
- public string html_url { get; set; }
- public string followers_url { get; set; }
- public string following_url { get; set; }
- public string gists_url { get; set; }
- public string starred_url { get; set; }
- public string subscriptions_url { get; set; }
- public string organizations_url { get; set; }
- public string repos_url { get; set; }
- public string events_url { get; set; }
- public string received_events_url { get; set; }
- public string type { get; set; }
- public bool site_admin { get; set; }
- }
-
- public class RootObject
- {
- public string url { get; set; }
- public string assets_url { get; set; }
- public string upload_url { get; set; }
- public string html_url { get; set; }
- public int id { get; set; }
- public string tag_name { get; set; }
- public string target_commitish { get; set; }
- public string name { get; set; }
- public bool draft { get; set; }
- public Author author { get; set; }
- public bool prerelease { get; set; }
- public string created_at { get; set; }
- public string published_at { get; set; }
- public List<Asset> assets { get; set; }
- public string tarball_url { get; set; }
- public string zipball_url { get; set; }
- public string body { get; set; }
- }
- }
-}
diff --git a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
index becb3ea62..82308296f 100644
--- a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
+++ b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Users;
diff --git a/MediaBrowser.Controller/Chapters/IChapterManager.cs b/MediaBrowser.Controller/Chapters/IChapterManager.cs
index 2a20eb365..161e87094 100644
--- a/MediaBrowser.Controller/Chapters/IChapterManager.cs
+++ b/MediaBrowser.Controller/Chapters/IChapterManager.cs
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-using System.Threading.Tasks;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.Chapters
@@ -10,12 +9,6 @@ namespace MediaBrowser.Controller.Chapters
public interface IChapterManager
{
/// <summary>
- /// Gets the chapters.
- /// </summary>
- /// <param name="itemId">The item identifier.</param>
- /// <returns>List{ChapterInfo}.</returns>
-
- /// <summary>
/// Saves the chapters.
/// </summary>
void SaveChapters(string itemId, List<ChapterInfo> chapters);
diff --git a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
index 727b487a7..5363e035c 100644
--- a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
+++ b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs
@@ -20,8 +20,8 @@ namespace MediaBrowser.Controller.Collections
public CollectionCreationOptions()
{
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ItemIdList = new string[] {};
- UserIds = new Guid[] {};
+ ItemIdList = Array.Empty<string>();
+ UserIds = Array.Empty<Guid>();
}
}
}
diff --git a/MediaBrowser.Controller/Connect/IConnectManager.cs b/MediaBrowser.Controller/Connect/IConnectManager.cs
deleted file mode 100644
index 8ac61bf2b..000000000
--- a/MediaBrowser.Controller/Connect/IConnectManager.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Model.Connect;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Controller.Connect
-{
- public interface IConnectManager
- {
- /// <summary>
- /// Gets the wan API address.
- /// </summary>
- /// <value>The wan API address.</value>
- string WanApiAddress { get; }
-
- /// <summary>
- /// Links the user.
- /// </summary>
- /// <param name="userId">The user identifier.</param>
- /// <param name="connectUsername">The connect username.</param>
- /// <returns>Task.</returns>
- Task<UserLinkResult> LinkUser(string userId, string connectUsername);
-
- /// <summary>
- /// Removes the link.
- /// </summary>
- /// <param name="userId">The user identifier.</param>
- /// <returns>Task.</returns>
- Task RemoveConnect(string userId);
-
- User GetUserFromExchangeToken(string token);
-
- /// <summary>
- /// Authenticates the specified username.
- /// </summary>
- Task<ConnectAuthenticationResult> Authenticate(string username, string password, string passwordMd5);
-
- /// <summary>
- /// Determines whether [is authorization token valid] [the specified token].
- /// </summary>
- /// <param name="token">The token.</param>
- /// <returns><c>true</c> if [is authorization token valid] [the specified token]; otherwise, <c>false</c>.</returns>
- bool IsAuthorizationTokenValid(string token);
- }
-}
diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs
index 219b36789..37e83e45a 100644
--- a/MediaBrowser.Controller/Dto/IDtoService.cs
+++ b/MediaBrowser.Controller/Dto/IDtoService.cs
@@ -2,7 +2,6 @@
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Querying;
using System.Collections.Generic;
-using MediaBrowser.Controller.Sync;
namespace MediaBrowser.Controller.Dto
{
diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs
index 4f4b3483c..a4601c270 100644
--- a/MediaBrowser.Controller/Entities/AggregateFolder.cs
+++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs
@@ -20,7 +20,7 @@ namespace MediaBrowser.Controller.Entities
{
public AggregateFolder()
{
- PhysicalLocationsList = new string[] { };
+ PhysicalLocationsList = Array.Empty<string>();
}
[IgnoreDataMember]
diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs
index d07e31d8a..1aeae6052 100644
--- a/MediaBrowser.Controller/Entities/Audio/Audio.cs
+++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs
@@ -2,13 +2,8 @@
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Serialization;
@@ -36,8 +31,8 @@ namespace MediaBrowser.Controller.Entities.Audio
public Audio()
{
- Artists = new string[] {};
- AlbumArtists = new string[] {};
+ Artists = Array.Empty<string>();
+ AlbumArtists = Array.Empty<string>();
}
public override double GetDefaultPrimaryImageAspectRatio()
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
index 48b5c64b2..870e6e07e 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs
@@ -23,8 +23,8 @@ namespace MediaBrowser.Controller.Entities.Audio
public MusicAlbum()
{
- Artists = new string[] {};
- AlbumArtists = new string[] {};
+ Artists = Array.Empty<string>();
+ AlbumArtists = Array.Empty<string>();
}
[IgnoreDataMember]
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
index 82dece84b..56ed10ced 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
@@ -1,5 +1,4 @@
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Users;
@@ -9,9 +8,8 @@ using System.Linq;
using MediaBrowser.Model.Serialization;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Extensions;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.Audio
{
@@ -131,13 +129,12 @@ namespace MediaBrowser.Controller.Entities.Audio
return base.IsSaveLocalMetadataEnabled();
}
- private readonly Task _cachedTask = Task.FromResult(true);
protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
{
if (IsAccessedByName)
{
// Should never get in here anyway
- return _cachedTask;
+ return Task.CompletedTask;
}
return base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
@@ -245,7 +242,7 @@ namespace MediaBrowser.Controller.Entities.Audio
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
}
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
index d60ce83ad..ec68eaf8b 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Serialization;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Extensions;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.Audio
{
@@ -119,7 +118,7 @@ namespace MediaBrowser.Controller.Entities.Audio
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index e3b5b5117..a268e6d76 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -1,41 +1,32 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Channels;
-using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Library;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Users;
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
-
-using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -44,24 +35,24 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>
{
- protected static MetadataFields[] EmptyMetadataFieldsArray = new MetadataFields[] { };
- protected static MediaUrl[] EmptyMediaUrlArray = new MediaUrl[] { };
- protected static ItemImageInfo[] EmptyItemImageInfoArray = new ItemImageInfo[] { };
- public static readonly LinkedChild[] EmptyLinkedChildArray = new LinkedChild[] { };
+ protected static MetadataFields[] EmptyMetadataFieldsArray = Array.Empty<MetadataFields>();
+ protected static MediaUrl[] EmptyMediaUrlArray = Array.Empty<MediaUrl>();
+ protected static ItemImageInfo[] EmptyItemImageInfoArray = Array.Empty<ItemImageInfo>();
+ public static readonly LinkedChild[] EmptyLinkedChildArray = Array.Empty<LinkedChild>();
protected BaseItem()
{
- ThemeSongIds = new Guid[] {};
- ThemeVideoIds = new Guid[] {};
- Tags = new string[] {};
- Genres = new string[] {};
- Studios = new string[] {};
+ ThemeSongIds = Array.Empty<Guid>();
+ ThemeVideoIds = Array.Empty<Guid>();
+ Tags = Array.Empty<string>();
+ Genres = Array.Empty<string>();
+ Studios = Array.Empty<string>();
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
LockedFields = EmptyMetadataFieldsArray;
ImageInfos = EmptyItemImageInfoArray;
- ProductionLocations = new string[] {};
- RemoteTrailers = new MediaUrl[] { };
- ExtraIds = new Guid[] {};
+ ProductionLocations = Array.Empty<string>();
+ RemoteTrailers = Array.Empty<MediaUrl>();
+ ExtraIds = Array.Empty<Guid>();
}
public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
@@ -71,7 +62,6 @@ namespace MediaBrowser.Controller.Entities
/// The supported image extensions
/// </summary>
public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
- public static readonly List<string> SupportedImageExtensionsList = SupportedImageExtensions.ToList();
/// <summary>
/// The trailer folder name
@@ -798,7 +788,7 @@ namespace MediaBrowser.Controller.Entities
builder.Append(chunkBuilder);
}
- //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
+ //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
return builder.ToString().RemoveDiacritics();
}
@@ -1414,7 +1404,7 @@ namespace MediaBrowser.Controller.Entities
}
catch (Exception ex)
{
- Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
+ Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
}
}
@@ -1802,7 +1792,7 @@ namespace MediaBrowser.Controller.Entities
if (!isAllowed)
{
- Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
+ Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
}
return isAllowed;
@@ -2058,7 +2048,7 @@ namespace MediaBrowser.Controller.Entities
if (itemByPath == null)
{
- //Logger.Warn("Unable to find linked item at path {0}", info.Path);
+ //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
}
return itemByPath;
@@ -2070,7 +2060,7 @@ namespace MediaBrowser.Controller.Entities
if (item == null)
{
- //Logger.Warn("Unable to find linked item at path {0}", info.Path);
+ //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
}
return item;
@@ -2213,7 +2203,7 @@ namespace MediaBrowser.Controller.Entities
/// <returns>Task.</returns>
public virtual void ChangedExternally()
{
- ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem)
+ ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem))
{
}, RefreshPriority.High);
@@ -2904,6 +2894,10 @@ namespace MediaBrowser.Controller.Entities
return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
}
+ /// <summary>
+ /// Gets or sets the remote trailers.
+ /// </summary>
+ /// <value>The remote trailers.</value>
public MediaUrl[] RemoteTrailers { get; set; }
public IEnumerable<BaseItem> GetExtras()
@@ -2922,21 +2916,24 @@ namespace MediaBrowser.Controller.Entities
}
public virtual bool IsHD {
- get{
+ get
+ {
return Height >= 720;
- }
+ }
}
public bool IsShortcut{ get; set;}
public string ShortcutPath{ get; set;}
public int Width { get; set; }
public int Height { get; set; }
public Guid[] ExtraIds { get; set; }
- public virtual long GetRunTimeTicksForPlayState() {
+ public virtual long GetRunTimeTicksForPlayState()
+ {
return RunTimeTicks ?? 0;
}
// what does this do?
public static ExtraType[] DisplayExtraTypes = new[] {Model.Entities.ExtraType.ThemeSong, Model.Entities.ExtraType.ThemeVideo };
- public virtual bool SupportsExternalTransfer {
+ public virtual bool SupportsExternalTransfer
+ {
get {
return false;
}
diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs
index 19a8c24b8..75d6b9381 100644
--- a/MediaBrowser.Controller/Entities/CollectionFolder.cs
+++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs
@@ -1,13 +1,13 @@
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using System;
+using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Controller.IO;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
@@ -15,6 +15,8 @@ using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
+
namespace MediaBrowser.Controller.Entities
{
/// <summary>
@@ -29,18 +31,10 @@ namespace MediaBrowser.Controller.Entities
public CollectionFolder()
{
- PhysicalLocationsList = new string[] { };
- PhysicalFolderIds = new Guid[] { };
+ PhysicalLocationsList = Array.Empty<string>();
+ PhysicalFolderIds = Array.Empty<Guid>();
}
- //public override double? GetDefaultPrimaryImageAspectRatio()
- //{
- // double value = 16;
- // value /= 9;
-
- // return value;
- //}
-
[IgnoreDataMember]
public override bool SupportsPlayedStatus
{
@@ -103,7 +97,7 @@ namespace MediaBrowser.Controller.Entities
}
catch (Exception ex)
{
- Logger.ErrorException("Error loading library options", ex);
+ Logger.LogError(ex, "Error loading library options");
return new LibraryOptions();
}
@@ -337,7 +331,7 @@ namespace MediaBrowser.Controller.Entities
/// <returns>Task.</returns>
protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
{
- return Task.FromResult(true);
+ return Task.CompletedTask;
}
/// <summary>
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index 81072b6e7..dbe30f9a5 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -10,7 +10,6 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities.Audio;
@@ -23,6 +22,7 @@ using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -264,7 +264,7 @@ namespace MediaBrowser.Controller.Entities
/// </summary>
protected virtual List<BaseItem> LoadChildren()
{
- //Logger.Debug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
+ //logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
//just load our children from the repo - the library will be validated and maintained in other processes
return GetCachedChildren();
}
@@ -303,7 +303,7 @@ namespace MediaBrowser.Controller.Entities
var id = child.Id;
if (dictionary.ContainsKey(id))
{
- Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
+ Logger.LogError("Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}",
Path ?? Name,
child.Path ?? child.Name);
}
@@ -371,6 +371,7 @@ namespace MediaBrowser.Controller.Entities
}
catch (Exception ex)
{
+ Logger.LogError(ex, "Error retrieving children folder");
return;
}
@@ -419,13 +420,9 @@ namespace MediaBrowser.Controller.Entities
foreach (var item in itemsRemoved)
{
- if (!item.IsFileProtocol)
- {
- }
-
- else
+ if (item.IsFileProtocol)
{
- Logger.Debug("Removed item: " + item.Path);
+ Logger.LogDebug("Removed item: " + item.Path);
item.SetParent(null);
LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false);
@@ -571,14 +568,9 @@ namespace MediaBrowser.Controller.Entities
await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
}
- if (recursive)
+ if (recursive && child is Folder folder)
{
- var folder = child as Folder;
-
- if (folder != null)
- {
- await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken);
- }
+ await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken);
}
}
}
@@ -782,7 +774,7 @@ namespace MediaBrowser.Controller.Entities
{
if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
{
- Logger.Debug("Query requires post-filtering due to BoxSet query");
+ Logger.LogDebug("Query requires post-filtering due to BoxSet query");
return true;
}
@@ -795,7 +787,7 @@ namespace MediaBrowser.Controller.Entities
{
if (!(this is ICollectionFolder))
{
- Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
+ Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
return true;
}
}
@@ -803,68 +795,68 @@ namespace MediaBrowser.Controller.Entities
// Filter by Video3DFormat
if (query.Is3D.HasValue)
{
- Logger.Debug("Query requires post-filtering due to Is3D");
+ Logger.LogDebug("Query requires post-filtering due to Is3D");
return true;
}
if (query.HasOfficialRating.HasValue)
{
- Logger.Debug("Query requires post-filtering due to HasOfficialRating");
+ Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
return true;
}
if (query.IsPlaceHolder.HasValue)
{
- Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
+ Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
return true;
}
if (query.HasSpecialFeature.HasValue)
{
- Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
+ Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
return true;
}
if (query.HasSubtitles.HasValue)
{
- Logger.Debug("Query requires post-filtering due to HasSubtitles");
+ Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
return true;
}
if (query.HasTrailer.HasValue)
{
- Logger.Debug("Query requires post-filtering due to HasTrailer");
+ Logger.LogDebug("Query requires post-filtering due to HasTrailer");
return true;
}
// Filter by VideoType
if (query.VideoTypes.Length > 0)
{
- Logger.Debug("Query requires post-filtering due to VideoTypes");
+ Logger.LogDebug("Query requires post-filtering due to VideoTypes");
return true;
}
if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
{
- Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
+ Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
return true;
}
if (!string.IsNullOrEmpty(query.AdjacentTo))
{
- Logger.Debug("Query requires post-filtering due to AdjacentTo");
+ Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
return true;
}
if (query.SeriesStatuses.Length > 0)
{
- Logger.Debug("Query requires post-filtering due to SeriesStatuses");
+ Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
return true;
}
if (query.AiredDuringSeason.HasValue)
{
- Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
+ Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
return true;
}
@@ -872,7 +864,7 @@ namespace MediaBrowser.Controller.Entities
{
if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
{
- Logger.Debug("Query requires post-filtering due to IsPlayed");
+ Logger.LogDebug("Query requires post-filtering due to IsPlayed");
return true;
}
}
@@ -1575,7 +1567,7 @@ namespace MediaBrowser.Controller.Entities
{
try
{
- Logger.Debug("Found shortcut at {0}", i.FullName);
+ Logger.LogDebug("Found shortcut at {0}", i.FullName);
var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
@@ -1588,13 +1580,13 @@ namespace MediaBrowser.Controller.Entities
};
}
- Logger.Error("Error resolving shortcut {0}", i.FullName);
+ Logger.LogError("Error resolving shortcut {0}", i.FullName);
return null;
}
catch (IOException ex)
{
- Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
+ Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
return null;
}
})
@@ -1605,7 +1597,7 @@ namespace MediaBrowser.Controller.Entities
if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
{
- Logger.Info("Shortcut links have changed for {0}", Path);
+ Logger.LogInformation("Shortcut links have changed for {0}", Path);
newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
LinkedChildren = newShortcutLinks.ToArray();
diff --git a/MediaBrowser.Controller/Entities/Game.cs b/MediaBrowser.Controller/Entities/Game.cs
index e4c417c8a..4efc5648e 100644
--- a/MediaBrowser.Controller/Entities/Game.cs
+++ b/MediaBrowser.Controller/Entities/Game.cs
@@ -1,11 +1,10 @@
-using MediaBrowser.Controller.Providers;
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using System;
-using System.Collections.Generic;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
-using System;
namespace MediaBrowser.Controller.Entities
{
@@ -13,10 +12,10 @@ namespace MediaBrowser.Controller.Entities
{
public Game()
{
- MultiPartGameFiles = new string[] {};
+ MultiPartGameFiles = Array.Empty<string>();
RemoteTrailers = EmptyMediaUrlArray;
- LocalTrailerIds = new Guid[] {};
- RemoteTrailerIds = new Guid[] {};
+ LocalTrailerIds = Array.Empty<Guid>();
+ RemoteTrailerIds = Array.Empty<Guid>();
}
public Guid[] LocalTrailerIds { get; set; }
@@ -40,12 +39,6 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Gets or sets the remote trailers.
- /// </summary>
- /// <value>The remote trailers.</value>
- public MediaUrl[] RemoteTrailers { get; set; }
-
- /// <summary>
/// Gets the type of the media.
/// </summary>
/// <value>The type of the media.</value>
diff --git a/MediaBrowser.Controller/Entities/GameGenre.cs b/MediaBrowser.Controller/Entities/GameGenre.cs
index 63493ad4a..ba178d3c3 100644
--- a/MediaBrowser.Controller/Entities/GameGenre.cs
+++ b/MediaBrowser.Controller/Entities/GameGenre.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Serialization;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Extensions;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -102,7 +101,7 @@ namespace MediaBrowser.Controller.Entities
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs
index 94a5984df..57ffe2744 100644
--- a/MediaBrowser.Controller/Entities/Genre.cs
+++ b/MediaBrowser.Controller/Entities/Genre.cs
@@ -2,9 +2,8 @@
using MediaBrowser.Controller.Entities.Audio;
using System;
using System.Collections.Generic;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Extensions;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -114,7 +113,7 @@ namespace MediaBrowser.Controller.Entities
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
index ff57c2471..bb99c0a84 100644
--- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
@@ -4,7 +4,6 @@ using System.Collections.Generic;
using MediaBrowser.Model.Configuration;
using System.Linq;
using MediaBrowser.Controller.Dto;
-using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.Entities
{
@@ -48,7 +47,6 @@ namespace MediaBrowser.Controller.Entities
public string PresentationUniqueKey { get; set; }
public string Path { get; set; }
- public string PathNotStartsWith { get; set; }
public string Name { get; set; }
public string Person { get; set; }
@@ -160,8 +158,6 @@ namespace MediaBrowser.Controller.Entities
public bool EnableGroupByMetadataKey { get; set; }
public bool? HasChapterImages { get; set; }
- // why tuple vs value tuple?
- //public Tuple<string, SortOrder>[] OrderBy { get; set; }
public ValueTuple<string, SortOrder>[] OrderBy { get; set; }
public DateTime? MinDateCreated { get; set; }
@@ -180,44 +176,44 @@ namespace MediaBrowser.Controller.Entities
public InternalItemsQuery()
{
- AlbumArtistIds = new Guid[] {};
- AlbumIds = new Guid[] {};
- AncestorIds = new Guid[] {};
- ArtistIds = new Guid[] {};
- BlockUnratedItems = new UnratedItem[] { };
- BoxSetLibraryFolders = new Guid[] {};
- ChannelIds = new Guid[] {};
- ContributingArtistIds = new Guid[] {};
+ AlbumArtistIds = Array.Empty<Guid>();
+ AlbumIds = Array.Empty<Guid>();
+ AncestorIds = Array.Empty<Guid>();
+ ArtistIds = Array.Empty<Guid>();
+ BlockUnratedItems = Array.Empty<UnratedItem>();
+ BoxSetLibraryFolders = Array.Empty<Guid>();
+ ChannelIds = Array.Empty<Guid>();
+ ContributingArtistIds = Array.Empty<Guid>();
DtoOptions = new DtoOptions();
EnableTotalRecordCount = true;
- ExcludeArtistIds = new Guid[] {};
- ExcludeInheritedTags = new string[] {};
- ExcludeItemIds = new Guid[] {};
- ExcludeItemTypes = new string[] {};
+ ExcludeArtistIds = Array.Empty<Guid>();
+ ExcludeInheritedTags = Array.Empty<string>();
+ ExcludeItemIds = Array.Empty<Guid>();
+ ExcludeItemTypes = Array.Empty<string>();
ExcludeProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ExcludeTags = new string[] {};
- GenreIds = new Guid[] {};
- Genres = new string[] {};
+ ExcludeTags = Array.Empty<string>();
+ GenreIds = Array.Empty<Guid>();
+ Genres = Array.Empty<string>();
GroupByPresentationUniqueKey = true;
HasAnyProviderId = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- ImageTypes = new ImageType[] { };
- IncludeItemTypes = new string[] {};
- ItemIds = new Guid[] {};
- MediaTypes = new string[] {};
+ ImageTypes = Array.Empty<ImageType>();
+ IncludeItemTypes = Array.Empty<string>();
+ ItemIds = Array.Empty<Guid>();
+ MediaTypes = Array.Empty<string>();
MinSimilarityScore = 20;
- OfficialRatings = new string[] {};
+ OfficialRatings = Array.Empty<string>();
OrderBy = Array.Empty<ValueTuple<string, SortOrder>>();
- PersonIds = new Guid[] {};
- PersonTypes = new string[] {};
- PresetViews = new string[] {};
- SeriesStatuses = new SeriesStatus[] { };
- SourceTypes = new SourceType[] { };
- StudioIds = new Guid[] {};
- Tags = new string[] {};
- TopParentIds = new Guid[] {};
- TrailerTypes = new TrailerType[] { };
- VideoTypes = new VideoType[] { };
- Years = new int[] { };
+ PersonIds = Array.Empty<Guid>();
+ PersonTypes = Array.Empty<string>();
+ PresetViews = Array.Empty<string>();
+ SeriesStatuses = Array.Empty<SeriesStatus>();
+ SourceTypes = Array.Empty<SourceType>();
+ StudioIds = Array.Empty<Guid>();
+ Tags = Array.Empty<string>();
+ TopParentIds = Array.Empty<Guid>();
+ TrailerTypes = Array.Empty<TrailerType>();
+ VideoTypes = Array.Empty<VideoType>();
+ Years = Array.Empty<int>();
}
public InternalItemsQuery(User user)
diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
index 7e00834e3..ce3e9e070 100644
--- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
@@ -14,8 +14,8 @@ namespace MediaBrowser.Controller.Entities
public InternalPeopleQuery()
{
- PersonTypes = new string[] { };
- ExcludePersonTypes = new string[] { };
+ PersonTypes = Array.Empty<string>();
+ ExcludePersonTypes = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
index 5918bf981..e888a5582 100644
--- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
+++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
@@ -19,8 +19,8 @@ namespace MediaBrowser.Controller.Entities.Movies
public BoxSet()
{
RemoteTrailers = EmptyMediaUrlArray;
- LocalTrailerIds = new Guid[] { };
- RemoteTrailerIds = new Guid[] { };
+ LocalTrailerIds = Array.Empty<Guid>();
+ RemoteTrailerIds = Array.Empty<Guid>();
DisplayOrder = ItemSortBy.PremiereDate;
}
@@ -53,12 +53,6 @@ namespace MediaBrowser.Controller.Entities.Movies
public Guid[] RemoteTrailerIds { get; set; }
/// <summary>
- /// Gets or sets the remote trailers.
- /// </summary>
- /// <value>The remote trailers.</value>
- public MediaUrl[] RemoteTrailers { get; set; }
-
- /// <summary>
/// Gets or sets the display order.
/// </summary>
/// <value>The display order.</value>
@@ -70,12 +64,7 @@ namespace MediaBrowser.Controller.Entities.Movies
}
public override double GetDefaultPrimaryImageAspectRatio()
- {
- double value = 2;
- value /= 3;
-
- return value;
- }
+ => 2 / 3;
public override UnratedItem GetBlockUnratedType()
{
@@ -254,7 +243,7 @@ namespace MediaBrowser.Controller.Entities.Movies
return FlattenItems(boxset.GetLinkedChildren(), expandedFolders);
}
- return new BaseItem[] { };
+ return Array.Empty<BaseItem>();
}
return new[] { item };
diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs
index 878b1b860..4f743991b 100644
--- a/MediaBrowser.Controller/Entities/Movies/Movie.cs
+++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs
@@ -6,8 +6,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
@@ -32,8 +30,6 @@ namespace MediaBrowser.Controller.Entities.Movies
public Guid[] LocalTrailerIds { get; set; }
public Guid[] RemoteTrailerIds { get; set; }
- public MediaUrl[] RemoteTrailers { get; set; }
-
/// <summary>
/// Gets or sets the name of the TMDB collection.
/// </summary>
@@ -55,10 +51,7 @@ namespace MediaBrowser.Controller.Entities.Movies
return 0;
}
- double value = 2;
- value /= 3;
-
- return value;
+ return 2 / 3;
}
protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs
index 78f9d0671..4015a1178 100644
--- a/MediaBrowser.Controller/Entities/MusicVideo.cs
+++ b/MediaBrowser.Controller/Entities/MusicVideo.cs
@@ -14,7 +14,7 @@ namespace MediaBrowser.Controller.Entities
public MusicVideo()
{
- Artists = new string[] {};
+ Artists = Array.Empty<string>();
}
[IgnoreDataMember]
diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs
index 64d775094..5c35a7411 100644
--- a/MediaBrowser.Controller/Entities/Person.cs
+++ b/MediaBrowser.Controller/Entities/Person.cs
@@ -1,11 +1,10 @@
using MediaBrowser.Controller.Providers;
using System;
using System.Collections.Generic;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -137,7 +136,7 @@ namespace MediaBrowser.Controller.Entities
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs
index 01c10831d..662aa4249 100644
--- a/MediaBrowser.Controller/Entities/Photo.cs
+++ b/MediaBrowser.Controller/Entities/Photo.cs
@@ -58,6 +58,7 @@ namespace MediaBrowser.Controller.Entities
public override double GetDefaultPrimaryImageAspectRatio()
{
+ // REVIEW: @bond
if (Width.HasValue && Height.HasValue)
{
double width = Width.Value;
@@ -85,8 +86,8 @@ namespace MediaBrowser.Controller.Entities
return base.GetDefaultPrimaryImageAspectRatio();
}
- public int? Width { get; set; }
- public int? Height { get; set; }
+ public new int? Width { get; set; }
+ public new int? Height { get; set; }
public string CameraMake { get; set; }
public string CameraModel { get; set; }
public string Software { get; set; }
diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs
index 29f617539..c076cd680 100644
--- a/MediaBrowser.Controller/Entities/Studio.cs
+++ b/MediaBrowser.Controller/Entities/Studio.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Serialization;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Extensions;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -115,7 +114,7 @@ namespace MediaBrowser.Controller.Entities
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs
index 201579731..00e055c51 100644
--- a/MediaBrowser.Controller/Entities/TV/Episode.cs
+++ b/MediaBrowser.Controller/Entities/TV/Episode.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Controller.Providers;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using System;
@@ -7,6 +7,7 @@ using System.Globalization;
using System.Linq;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.TV
{
@@ -18,13 +19,12 @@ namespace MediaBrowser.Controller.Entities.TV
public Episode()
{
RemoteTrailers = EmptyMediaUrlArray;
- LocalTrailerIds = new Guid[] {};
- RemoteTrailerIds = new Guid[] {};
+ LocalTrailerIds = Array.Empty<Guid>();
+ RemoteTrailerIds = Array.Empty<Guid>();
}
public Guid[] LocalTrailerIds { get; set; }
public Guid[] RemoteTrailerIds { get; set; }
- public MediaUrl[] RemoteTrailers { get; set; }
/// <summary>
/// Gets the season in which it aired.
@@ -111,10 +111,7 @@ namespace MediaBrowser.Controller.Entities.TV
return 0;
}
- double value = 16;
- value /= 9;
-
- return value;
+ return 16 / 9;
}
public override List<string> GetUserDataKeys()
@@ -363,7 +360,7 @@ namespace MediaBrowser.Controller.Entities.TV
}
catch (Exception ex)
{
- Logger.ErrorException("Error in FillMissingEpisodeNumbersFromPath. Episode: {0}", ex, Path ?? Name ?? Id.ToString());
+ Logger.LogError(ex, "Error in FillMissingEpisodeNumbersFromPath. Episode: {Episode}", Path ?? Name ?? Id.ToString());
}
}
}
diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs
index b5f77df55..cb3a7f345 100644
--- a/MediaBrowser.Controller/Entities/TV/Season.cs
+++ b/MediaBrowser.Controller/Entities/TV/Season.cs
@@ -102,10 +102,11 @@ namespace MediaBrowser.Controller.Entities.TV
get
{
var seriesId = SeriesId;
- if (seriesId.Equals(Guid.Empty)) {
+ if (seriesId == Guid.Empty)
+ {
seriesId = FindSeriesId();
}
- return !seriesId.Equals(Guid.Empty) ? (LibraryManager.GetItemById(seriesId) as Series) : null;
+ return seriesId == Guid.Empty ? null : (LibraryManager.GetItemById(seriesId) as Series);
}
}
@@ -227,7 +228,7 @@ namespace MediaBrowser.Controller.Entities.TV
public Guid FindSeriesId()
{
var series = FindParent<Series>();
- return series == null ? Guid.Empty: series.Id;
+ return series == null ? Guid.Empty : series.Id;
}
/// <summary>
diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs
index 88fde1760..d4a62626e 100644
--- a/MediaBrowser.Controller/Entities/TV/Series.cs
+++ b/MediaBrowser.Controller/Entities/TV/Series.cs
@@ -23,9 +23,9 @@ namespace MediaBrowser.Controller.Entities.TV
public Series()
{
RemoteTrailers = EmptyMediaUrlArray;
- LocalTrailerIds = new Guid[] {};
- RemoteTrailerIds = new Guid[] {};
- AirDays = new DayOfWeek[] { };
+ LocalTrailerIds = Array.Empty<Guid>();
+ RemoteTrailerIds = Array.Empty<Guid>();
+ AirDays = Array.Empty<DayOfWeek>();
}
public DayOfWeek[] AirDays { get; set; }
@@ -73,8 +73,6 @@ namespace MediaBrowser.Controller.Entities.TV
public Guid[] LocalTrailerIds { get; set; }
public Guid[] RemoteTrailerIds { get; set; }
- public MediaUrl[] RemoteTrailers { get; set; }
-
/// <summary>
/// airdate, dvd or absolute
/// </summary>
diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs
index 4f2a5631b..2ef268ed1 100644
--- a/MediaBrowser.Controller/Entities/Trailer.cs
+++ b/MediaBrowser.Controller/Entities/Trailer.cs
@@ -15,18 +15,13 @@ namespace MediaBrowser.Controller.Entities
{
public Trailer()
{
- TrailerTypes = new TrailerType[] { };
+ TrailerTypes = Array.Empty<TrailerType>();
}
public TrailerType[] TrailerTypes { get; set; }
public override double GetDefaultPrimaryImageAspectRatio()
- {
- double value = 2;
- value /= 3;
-
- return value;
- }
+ => 2 / 3;
public override UnratedItem GetBlockUnratedType()
{
diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs
index 984cad481..b7c9884ff 100644
--- a/MediaBrowser.Controller/Entities/UserView.cs
+++ b/MediaBrowser.Controller/Entities/UserView.cs
@@ -1,21 +1,18 @@
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.TV;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Model.Serialization;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Collections;
namespace MediaBrowser.Controller.Entities
{
public class UserView : Folder, IHasCollectionType
{
public string ViewType { get; set; }
- public Guid DisplayParentId { get; set; }
+ public new Guid DisplayParentId { get; set; }
public Guid? UserId { get; set; }
@@ -68,14 +65,6 @@ namespace MediaBrowser.Controller.Entities
}
}
- //public override double? GetDefaultPrimaryImageAspectRatio()
- //{
- // double value = 16;
- // value /= 9;
-
- // return value;
- //}
-
public override int GetChildCount(User user)
{
return GetChildren(user, true).Count;
@@ -161,8 +150,8 @@ namespace MediaBrowser.Controller.Entities
public static bool IsEligibleForGrouping(Folder folder)
{
- var collectionFolder = folder as ICollectionFolder;
- return collectionFolder != null && IsEligibleForGrouping(collectionFolder.CollectionType);
+ return folder is ICollectionFolder collectionFolder
+ && IsEligibleForGrouping(collectionFolder.CollectionType);
}
private static string[] ViewTypesEligibleForGrouping = new string[]
@@ -195,7 +184,7 @@ namespace MediaBrowser.Controller.Entities
protected override Task ValidateChildrenInternal(IProgress<double> progress, System.Threading.CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, Providers.MetadataRefreshOptions refreshOptions, Providers.IDirectoryService directoryService)
{
- return Task.FromResult(true);
+ return Task.CompletedTask;
}
[IgnoreDataMember]
diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
index 36035a2bb..b50a12d52 100644
--- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs
+++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
@@ -259,10 +259,9 @@ namespace MediaBrowser.Controller.Entities
{
return _libraryManager.GetGenre(i);
}
- catch
+ catch (Exception ex)
{
- // Full exception logged at lower levels
- _logger.Error("Error getting genre");
+ _logger.LogError(ex, "Error getting genre");
return null;
}
@@ -383,10 +382,9 @@ namespace MediaBrowser.Controller.Entities
{
return _libraryManager.GetGenre(i);
}
- catch
+ catch (Exception ex)
{
- // Full exception logged at lower levels
- _logger.Error("Error getting genre");
+ _logger.LogError(ex, "Error getting genre");
return null;
}
diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs
index 65f5b8382..2db200ee2 100644
--- a/MediaBrowser.Controller/Entities/Video.cs
+++ b/MediaBrowser.Controller/Entities/Video.cs
@@ -10,7 +10,6 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Extensions;
@@ -132,8 +131,6 @@ namespace MediaBrowser.Controller.Entities
public bool HasSubtitles { get; set; }
public bool IsPlaceHolder { get; set; }
- public bool IsShortcut { get; set; }
- public string ShortcutPath { get; set; }
/// <summary>
/// Gets or sets the default index of the video stream.
@@ -173,7 +170,7 @@ namespace MediaBrowser.Controller.Entities
}
else
{
- return new string[] {};
+ return Array.Empty<string>();
}
return mediaEncoder.GetPlayableStreamFileNames(Path, videoType);
}
@@ -186,9 +183,9 @@ namespace MediaBrowser.Controller.Entities
public Video()
{
- AdditionalParts = new string[] {};
- LocalAlternateVersions = new string[] {};
- SubtitleFiles = new string[] {};
+ AdditionalParts = Array.Empty<string>();
+ LocalAlternateVersions = Array.Empty<string>();
+ SubtitleFiles = Array.Empty<string>();
LinkedAlternateVersions = EmptyLinkedChildArray;
}
@@ -215,10 +212,10 @@ namespace MediaBrowser.Controller.Entities
{
if (!string.IsNullOrEmpty(PrimaryVersionId))
{
- var item = LibraryManager.GetItemById(PrimaryVersionId) as Video;
- if (item != null)
+ var item = LibraryManager.GetItemById(PrimaryVersionId);
+ if (item is Video video)
{
- return item.MediaSourceCount;
+ return video.MediaSourceCount;
}
}
return LinkedAlternateVersions.Length + LocalAlternateVersions.Length + 1;
@@ -366,7 +363,7 @@ namespace MediaBrowser.Controller.Entities
/// Gets the additional parts.
/// </summary>
/// <returns>IEnumerable{Video}.</returns>
- public IEnumerable<Video> GetAdditionalParts()
+ public IOrderedEnumerable<Video> GetAdditionalParts()
{
return GetAdditionalPartIds()
.Select(i => LibraryManager.GetItemById(i))
@@ -420,8 +417,7 @@ namespace MediaBrowser.Controller.Entities
{
var updateType = base.UpdateFromResolvedItem(newItem);
- var newVideo = newItem as Video;
- if (newVideo != null)
+ if (newItem is Video newVideo)
{
if (!AdditionalParts.SequenceEqual(newVideo.AdditionalParts, StringComparer.Ordinal))
{
@@ -463,7 +459,7 @@ namespace MediaBrowser.Controller.Entities
.Select(i => i.FullName)
.ToArray();
}
- return new string[] {};
+ return Array.Empty<string>();
}
/// <summary>
@@ -618,9 +614,5 @@ namespace MediaBrowser.Controller.Entities
return list;
}
-
- public static bool IsHD (Video video) {
- return video.Height >= 720;
- }
}
}
diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs
index 81e030cea..8e3cd0b70 100644
--- a/MediaBrowser.Controller/Entities/Year.cs
+++ b/MediaBrowser.Controller/Entities/Year.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
{
@@ -121,7 +122,7 @@ namespace MediaBrowser.Controller.Entities
var newPath = GetRebasedPath();
if (!string.Equals(Path, newPath, StringComparison.Ordinal))
{
- Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
+ Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath);
return true;
}
return base.RequiresRefresh();
diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs
index e1fabee4f..c0cf51ab2 100644
--- a/MediaBrowser.Controller/IO/FileData.cs
+++ b/MediaBrowser.Controller/IO/FileData.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MediaBrowser.Model.IO;
@@ -77,7 +77,7 @@ namespace MediaBrowser.Controller.IO
if (string.IsNullOrEmpty(newPath))
{
//invalid shortcut - could be old or target could just be unavailable
- logger.Warn("Encountered invalid shortcut: " + fullName);
+ logger.LogWarning("Encountered invalid shortcut: " + fullName);
continue;
}
@@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.IO
}
catch (Exception ex)
{
- logger.ErrorException("Error resolving shortcut from {0}", ex, fullName);
+ logger.LogError(ex, "Error resolving shortcut from {path}", fullName);
}
}
else if (flattenFolderDepth > 0 && isDirectory)
diff --git a/MediaBrowser.Controller/IResourceFileManager.cs b/MediaBrowser.Controller/IResourceFileManager.cs
index ae73f4b4c..64f1b9f7a 100644
--- a/MediaBrowser.Controller/IResourceFileManager.cs
+++ b/MediaBrowser.Controller/IResourceFileManager.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using System;
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index 830c160e3..4dc559031 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -24,12 +24,6 @@ namespace MediaBrowser.Controller
Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken);
- /// <summary>
- /// Gets a value indicating whether [supports automatic run at startup].
- /// </summary>
- /// <value><c>true</c> if [supports automatic run at startup]; otherwise, <c>false</c>.</value>
- bool SupportsAutoRunAtStartup { get; }
-
bool CanLaunchWebBrowser { get; }
/// <summary>
diff --git a/MediaBrowser.Controller/Library/IUserDataManager.cs b/MediaBrowser.Controller/Library/IUserDataManager.cs
index 11d77f81a..f3f81378b 100644
--- a/MediaBrowser.Controller/Library/IUserDataManager.cs
+++ b/MediaBrowser.Controller/Library/IUserDataManager.cs
@@ -5,7 +5,6 @@ using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using System;
using System.Threading;
-using MediaBrowser.Model.Querying;
namespace MediaBrowser.Controller.Library
{
diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
index 7197425f3..9812802e7 100644
--- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs
+++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
@@ -2,10 +2,7 @@
using MediaBrowser.Controller.Providers;
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
@@ -169,6 +166,7 @@ namespace MediaBrowser.Controller.Library
AdditionalLocations.Add(path);
}
+ // REVIEW: @bond
/// <summary>
/// Gets the physical locations.
/// </summary>
@@ -177,7 +175,7 @@ namespace MediaBrowser.Controller.Library
{
get
{
- var paths = string.IsNullOrEmpty(Path) ? new string[] { } : new[] { Path };
+ var paths = string.IsNullOrEmpty(Path) ? Array.Empty<string>() : new[] { Path };
return AdditionalLocations == null ? paths : paths.Concat(AdditionalLocations).ToArray();
}
}
@@ -261,7 +259,7 @@ namespace MediaBrowser.Controller.Library
}
/// <summary>
- /// Equalses the specified args.
+ /// Equals the specified args.
/// </summary>
/// <param name="args">The args.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs
index 3957c3020..745e49920 100644
--- a/MediaBrowser.Controller/Library/Profiler.cs
+++ b/MediaBrowser.Controller/Library/Profiler.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
@@ -67,7 +67,7 @@ namespace MediaBrowser.Controller.Library
message = string.Format("{0} took {1} seconds.",
_name, ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000"));
}
- _logger.Info(message);
+ _logger.LogInformation(message);
}
}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
index fa3aab4f2..4dc6c7517 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs
@@ -47,52 +47,21 @@ namespace MediaBrowser.Controller.LiveTv
return list;
}
- public static double GetDefaultPrimaryImageAspectRatio(IHasProgramAttributes item)
+ private static string EmbyServiceName = "Emby";
+ public override double GetDefaultPrimaryImageAspectRatio()
{
- var serviceName = item.ServiceName;
+ var serviceName = ServiceName;
- if (item.IsMovie)
+ if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
{
- if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
- {
- double value = 2;
- value /= 3;
-
- return value;
- }
- else
- {
- double value = 16;
- value /= 9;
-
- return value;
- }
+ return 2 / 3;
}
else
{
- if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
- {
- double value = 2;
- value /= 3;
-
- return value;
- }
- else
- {
- double value = 16;
- value /= 9;
-
- return value;
- }
+ return 16 / 9;
}
}
- private static string EmbyServiceName = "Emby";
- public override double GetDefaultPrimaryImageAspectRatio()
- {
- return GetDefaultPrimaryImageAspectRatio(this);
- }
-
[IgnoreDataMember]
public override SourceType SourceType
{
diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
index baf0b0b13..c9eb6fee6 100644
--- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
@@ -10,11 +10,11 @@ namespace MediaBrowser.Controller.LiveTv
{
public TimerInfo()
{
- Genres = new string[] { };
+ Genres = Array.Empty<string>();
KeepUntil = KeepUntil.UntilDeleted;
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
SeriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- Tags = new string[] { };
+ Tags = Array.Empty<string>();
}
public Dictionary<string, string> ProviderIds { get; set; }
diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
index 8e816080c..4567f62dd 100644
--- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj
+++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 881e318ce..4fb9a711e 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Threading;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
@@ -12,8 +11,6 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Reflection;
namespace MediaBrowser.Controller.MediaEncoding
{
@@ -343,19 +340,19 @@ namespace MediaBrowser.Controller.MediaEncoding
public int GetVideoProfileScore(string profile)
{
- var list = new []
+ string[] list =
{
- "Constrained Baseline",
+ "ConstrainedBaseline",
"Baseline",
"Extended",
"Main",
"High",
- "Progressive High",
- "Constrained High"
+ "ProgressiveHigh",
+ "ConstrainedHigh"
};
// strip spaces because they may be stripped out on the query string
- return Array.FindIndex(list, t => string.Equals(t.Replace(" ", ""), profile.Replace(" ", ""), StringComparison.OrdinalIgnoreCase));
+ return Array.FindIndex(list, t => string.Equals(t, profile.Replace(" ", ""), StringComparison.OrdinalIgnoreCase));
}
public string GetInputPathArgument(EncodingJobInfo state)
@@ -516,18 +513,12 @@ namespace MediaBrowser.Controller.MediaEncoding
public string NormalizeTranscodingLevel(string videoCodec, string level)
{
- double requestLevel;
-
// Clients may direct play higher than level 41, but there's no reason to transcode higher
- if (double.TryParse(level, NumberStyles.Any, _usCulture, out requestLevel))
+ if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)
+ && string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)
+ && requestLevel > 41)
{
- if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
- {
- if (requestLevel > 41)
- {
- return "41";
- }
- }
+ return "41";
}
return level;
@@ -623,7 +614,7 @@ namespace MediaBrowser.Controller.MediaEncoding
// h264 (h264_qsv)
else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
{
- string[] valid_h264_qsv = new string[] { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
+ string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
if (valid_h264_qsv.Contains(encodingOptions.H264Preset, StringComparer.OrdinalIgnoreCase))
{
@@ -1958,12 +1949,12 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else
{
- state.PlayableStreamFileNames = new string[] { };
+ state.PlayableStreamFileNames = Array.Empty<string>();
}
}
else
{
- state.PlayableStreamFileNames = new string[] { };
+ state.PlayableStreamFileNames = Array.Empty<string>();
}
if (mediaSource.Timestamp.HasValue)
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
index 3d2871e65..3f6da59d8 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
@@ -8,10 +8,10 @@ using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.MediaEncoding
{
@@ -207,7 +207,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
- return new string[] { };
+ return Array.Empty<string>();
}
public string GetRequestedLevel(string codec)
@@ -317,10 +317,10 @@ namespace MediaBrowser.Controller.MediaEncoding
_logger = logger;
TranscodingType = jobType;
RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- PlayableStreamFileNames = new string[] { };
- SupportedAudioCodecs = new string[] { };
- SupportedVideoCodecs = new string[] { };
- SupportedSubtitleCodecs = new string[] { };
+ PlayableStreamFileNames = Array.Empty<string>();
+ SupportedAudioCodecs = Array.Empty<string>();
+ SupportedVideoCodecs = Array.Empty<string>();
+ SupportedSubtitleCodecs = Array.Empty<string>();
}
public bool IsSegmentedLiveStream
@@ -727,7 +727,6 @@ namespace MediaBrowser.Controller.MediaEncoding
return count;
}
-
protected void DisposeIsoMount()
{
if (IsoMount != null)
@@ -738,7 +737,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing iso mount", ex);
+ _logger.LogError(ex, "Error disposing iso mount");
}
IsoMount = null;
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs
index 7333149c2..101748a5a 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs
@@ -10,14 +10,10 @@ namespace MediaBrowser.Controller.MediaEncoding
public class EncodingJobOptions : BaseEncodingJobOptions
{
public string OutputDirectory { get; set; }
-
- public string DeviceId { get; set; }
public string ItemId { get; set; }
public string MediaSourceId { get; set; }
public string AudioCodec { get; set; }
- public DeviceProfile DeviceProfile { get; set; }
-
public bool ReadInputAtNativeFramerate { get; set; }
/// <summary>
diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
index 5f3f79d77..8bb826bd1 100644
--- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
+++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
@@ -1,10 +1,10 @@
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.MediaEncoding
{
@@ -43,7 +43,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
catch (Exception ex)
{
- _logger.ErrorException("Error reading ffmpeg log", ex);
+ _logger.LogError(ex, "Error reading ffmpeg log");
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
index 1d7222801..b191f9905 100644
--- a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
+++ b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs
@@ -18,7 +18,7 @@ namespace MediaBrowser.Controller.MediaEncoding
public MediaInfoRequest()
{
- PlayableStreamFileNames = new string[] {};
+ PlayableStreamFileNames = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
index a68060db5..848d8fa15 100644
--- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs
+++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
@@ -1,7 +1,6 @@
using MediaBrowser.Controller.Entities;
using System;
-
namespace MediaBrowser.Controller.Net
{
public class AuthorizationInfo
@@ -12,12 +11,7 @@ namespace MediaBrowser.Controller.Net
/// <value>The user identifier.</value>
public Guid UserId {
get {
- if (User == null) {
- return Guid.Empty;
- }
- else {
- return User.Id;
- }
+ return User == null ? Guid.Empty : User.Id;
}
}
diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
index 7df96b777..31ec149bf 100644
--- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
+++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
@@ -1,5 +1,4 @@
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Net;
using MediaBrowser.Model.Threading;
using System.Collections.Generic;
using System.Globalization;
@@ -8,6 +7,7 @@ using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Threading;
using System;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Net
{
@@ -114,7 +114,7 @@ namespace MediaBrowser.Controller.Net
var cancellationTokenSource = new CancellationTokenSource();
- Logger.Debug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
+ Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
var timer = SendOnTimer ?
TimerFactory.Create(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) :
@@ -229,7 +229,7 @@ namespace MediaBrowser.Controller.Net
}
catch (Exception ex)
{
- Logger.ErrorException("Error sending web socket message {0}", ex, Name);
+ Logger.LogError(ex, "Error sending web socket message {Name}", Name);
DisposeConnection(tuple);
}
}
@@ -257,7 +257,7 @@ namespace MediaBrowser.Controller.Net
/// <param name="connection">The connection.</param>
private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType> connection)
{
- Logger.Debug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
+ Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
var timer = connection.Item3;
diff --git a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs b/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs
index b200f883a..26abbc2d2 100644
--- a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs
+++ b/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Specialized;
using MediaBrowser.Model.Services;
namespace MediaBrowser.Controller.Net
@@ -7,7 +6,6 @@ namespace MediaBrowser.Controller.Net
/// <summary>
/// Class WebSocketConnectEventArgs
/// </summary>
-
public class WebSocketConnectingEventArgs : EventArgs
{
/// <summary>
diff --git a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
index 5e790111d..d481bf7c5 100644
--- a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
+++ b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs
@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using System;
-
namespace MediaBrowser.Controller.Playlists
{
public interface IPlaylistManager
diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs
index 78614340a..642dfde80 100644
--- a/MediaBrowser.Controller/Playlists/Playlist.cs
+++ b/MediaBrowser.Controller/Playlists/Playlist.cs
@@ -15,14 +15,14 @@ namespace MediaBrowser.Controller.Playlists
{
public class Playlist : Folder, IHasShares
{
- public static string[] SupportedExtensions = new string[] {
-
- ".m3u",
- ".m3u8",
- ".pls",
- ".wpl",
- ".zpl"
- };
+ public static string[] SupportedExtensions =
+ {
+ ".m3u",
+ ".m3u8",
+ ".pls",
+ ".wpl",
+ ".zpl"
+ };
public Guid OwnerUserId { get; set; }
@@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.Playlists
public Playlist()
{
- Shares = new Share[] { };
+ Shares = Array.Empty<Share>();
}
[IgnoreDataMember]
@@ -131,7 +131,7 @@ namespace MediaBrowser.Controller.Playlists
protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
{
- return Task.FromResult(true);
+ return Task.CompletedTask;
}
public override List<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
@@ -186,8 +186,7 @@ namespace MediaBrowser.Controller.Playlists
private static IEnumerable<BaseItem> GetPlaylistItems(BaseItem item, User user, string mediaType, DtoOptions options)
{
- var musicGenre = item as MusicGenre;
- if (musicGenre != null)
+ if (item is MusicGenre musicGenre)
{
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
@@ -199,8 +198,7 @@ namespace MediaBrowser.Controller.Playlists
});
}
- var musicArtist = item as MusicArtist;
- if (musicArtist != null)
+ if (item is MusicArtist musicArtist)
{
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
@@ -212,8 +210,7 @@ namespace MediaBrowser.Controller.Playlists
});
}
- var folder = item as Folder;
- if (folder != null)
+ if (item is Folder folder)
{
var query = new InternalItemsQuery(user)
{
diff --git a/MediaBrowser.Controller/Providers/AlbumInfo.cs b/MediaBrowser.Controller/Providers/AlbumInfo.cs
index 74feb4ea2..b0b443fc0 100644
--- a/MediaBrowser.Controller/Providers/AlbumInfo.cs
+++ b/MediaBrowser.Controller/Providers/AlbumInfo.cs
@@ -22,7 +22,7 @@ namespace MediaBrowser.Controller.Providers
{
ArtistProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
SongInfos = new List<SongInfo>();
- AlbumArtists = EmptyStringArray;
+ AlbumArtists = Array.Empty<string>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs
index 65192671e..9bb2f5bed 100644
--- a/MediaBrowser.Controller/Providers/DirectoryService.cs
+++ b/MediaBrowser.Controller/Providers/DirectoryService.cs
@@ -1,10 +1,7 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
namespace MediaBrowser.Controller.Providers
@@ -26,18 +23,13 @@ namespace MediaBrowser.Controller.Providers
_fileSystem = fileSystem;
}
- public DirectoryService(IFileSystem fileSystem)
- : this(new NullLogger(), fileSystem)
- {
- }
-
public FileSystemMetadata[] GetFileSystemEntries(string path)
{
FileSystemMetadata[] entries;
if (!_cache.TryGetValue(path, out entries))
{
- //_logger.Debug("Getting files for " + path);
+ //_logger.LogDebug("Getting files for " + path);
entries = _fileSystem.GetFileSystemEntries(path).ToArray();
diff --git a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
index 942d25071..6cc8a691e 100644
--- a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
+++ b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs
@@ -20,7 +20,7 @@ namespace MediaBrowser.Controller.Providers
ImageRefreshMode = MetadataRefreshMode.Default;
DirectoryService = directoryService;
- ReplaceImages = new ImageType[] { };
+ ReplaceImages = Array.Empty<ImageType>();
IsAutomated = true;
}
@@ -30,4 +30,4 @@ namespace MediaBrowser.Controller.Providers
(ReplaceAllImages || ReplaceImages.Contains(type));
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
index 98122e776..dc7a04135 100644
--- a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
+++ b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs
@@ -6,8 +6,6 @@ namespace MediaBrowser.Controller.Providers
{
public class ItemLookupInfo : IHasProviderIds
{
- protected static string[] EmptyStringArray = new string[] { };
-
/// <summary>
/// Gets or sets the name.
/// </summary>
diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
index 3e34075a6..3dbcc5305 100644
--- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
+++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs
@@ -1,10 +1,8 @@
using System;
-using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
namespace MediaBrowser.Controller.Providers
@@ -24,11 +22,6 @@ namespace MediaBrowser.Controller.Providers
public bool ForceSave { get; set; }
public bool EnableRemoteContentProbe { get; set; }
- public MetadataRefreshOptions(IFileSystem fileSystem)
- : this(new DirectoryService(new NullLogger(), fileSystem))
- {
- }
-
public MetadataRefreshOptions(IDirectoryService directoryService)
: base(directoryService)
{
@@ -52,7 +45,7 @@ namespace MediaBrowser.Controller.Providers
{
if (RefreshPaths == null)
{
- RefreshPaths = new string[] { };
+ RefreshPaths = Array.Empty<string>();
}
RefreshPaths = copy.RefreshPaths.ToArray();
diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs
index f35d41ca4..271f784d7 100644
--- a/MediaBrowser.Controller/Providers/MetadataResult.cs
+++ b/MediaBrowser.Controller/Providers/MetadataResult.cs
@@ -74,4 +74,4 @@ namespace MediaBrowser.Controller.Providers
return userData;
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Controller/Providers/SongInfo.cs b/MediaBrowser.Controller/Providers/SongInfo.cs
index e3a6f5d37..61e950130 100644
--- a/MediaBrowser.Controller/Providers/SongInfo.cs
+++ b/MediaBrowser.Controller/Providers/SongInfo.cs
@@ -1,3 +1,4 @@
+using System;
namespace MediaBrowser.Controller.Providers
{
@@ -9,8 +10,8 @@ namespace MediaBrowser.Controller.Providers
public SongInfo()
{
- Artists = EmptyStringArray;
- AlbumArtists = EmptyStringArray;
+ Artists = Array.Empty<string>();
+ AlbumArtists = Array.Empty<string>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Controller/Session/AuthenticationRequest.cs b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
index eb64db8c3..0489cf9b6 100644
--- a/MediaBrowser.Controller/Session/AuthenticationRequest.cs
+++ b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
@@ -1,6 +1,5 @@
using System;
-
namespace MediaBrowser.Controller.Session
{
public class AuthenticationRequest
@@ -9,7 +8,6 @@ namespace MediaBrowser.Controller.Session
public Guid UserId { get; set; }
public string Password { get; set; }
public string PasswordSha1 { get; set; }
- public string PasswordMd5 { get; set; }
public string App { get; set; }
public string AppVersion { get; set; }
public string DeviceId { get; set; }
diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs
index b7719e556..eca345cbc 100644
--- a/MediaBrowser.Controller/Session/ISessionManager.cs
+++ b/MediaBrowser.Controller/Session/ISessionManager.cs
@@ -5,7 +5,6 @@ using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Session;
-using MediaBrowser.Model.Users;
using System;
using System.Collections.Generic;
using System.Threading;
diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs
index 869d3fcb0..77e786ead 100644
--- a/MediaBrowser.Controller/Session/SessionInfo.cs
+++ b/MediaBrowser.Controller/Session/SessionInfo.cs
@@ -1,11 +1,11 @@
-using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
+using System;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Threading;
using System.Linq;
-using System;
namespace MediaBrowser.Controller.Session
{
@@ -22,9 +22,9 @@ namespace MediaBrowser.Controller.Session
_sessionManager = sessionManager;
_logger = logger;
- AdditionalUsers = new SessionUserInfo[] { };
+ AdditionalUsers = Array.Empty<SessionUserInfo>();
PlayState = new PlayerStateInfo();
- SessionControllers = new ISessionController[] { };
+ SessionControllers = Array.Empty<ISessionController>();
}
public PlayerStateInfo PlayState { get; set; }
@@ -49,7 +49,7 @@ namespace MediaBrowser.Controller.Session
{
if (Capabilities == null)
{
- return new string[] {};
+ return Array.Empty<string>();
}
return Capabilities.PlayableMediaTypes;
}
@@ -231,7 +231,7 @@ namespace MediaBrowser.Controller.Session
}
var newController = factory(this);
- _logger.Debug("Creating new {0}", newController.GetType().Name);
+ _logger.LogDebug("Creating new {0}", newController.GetType().Name);
controllers.Add(newController);
SessionControllers = controllers.ToArray();
@@ -337,7 +337,7 @@ namespace MediaBrowser.Controller.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error reporting playback progress", ex);
+ _logger.LogError(ex, "Error reporting playback progress");
}
}
@@ -363,7 +363,7 @@ namespace MediaBrowser.Controller.Session
StopAutomaticProgress();
var controllers = SessionControllers.ToList();
- SessionControllers = new ISessionController[] { };
+ SessionControllers = Array.Empty<ISessionController>();
foreach (var controller in controllers)
{
@@ -371,7 +371,7 @@ namespace MediaBrowser.Controller.Session
if (disposable != null)
{
- _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);
+ _logger.LogDebug("Disposing session controller {0}", disposable.GetType().Name);
try
{
@@ -379,7 +379,7 @@ namespace MediaBrowser.Controller.Session
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing session controller", ex);
+ _logger.LogError(ex, "Error disposing session controller");
}
}
}
diff --git a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
index 84bf28c05..daef6db79 100644
--- a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
+++ b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs
@@ -32,8 +32,8 @@ namespace MediaBrowser.Controller.Subtitles
SearchAllProviders = true;
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- DisabledSubtitleFetchers = new string[] {};
- SubtitleFetcherOrder = new string[] {};
+ DisabledSubtitleFetchers = Array.Empty<string>();
+ SubtitleFetcherOrder = Array.Empty<string>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
index 1fbdcf39a..e46709b78 100644
--- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
@@ -77,12 +77,12 @@ namespace MediaBrowser.LocalMetadata.Images
return directoryService.GetFileSystemEntries(path)
.Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase) || i.IsDirectory)
- .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));
+ .OrderBy(i => Array.IndexOf(BaseItem.SupportedImageExtensions, i.Extension ?? string.Empty));
}
return directoryService.GetFiles(path)
.Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
- .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));
+ .OrderBy(i => Array.IndexOf(BaseItem.SupportedImageExtensions, i.Extension ?? string.Empty));
}
public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
@@ -106,7 +106,7 @@ namespace MediaBrowser.LocalMetadata.Images
IEnumerable<FileSystemMetadata> files = paths.SelectMany(i => _fileSystem.GetFiles(i, BaseItem.SupportedImageExtensions, true, false));
files = files
- .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));
+ .OrderBy(i => Array.IndexOf(BaseItem.SupportedImageExtensions, i.Extension ?? string.Empty));
var list = new List<LocalImageInfo>();
diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
index bdf2f9873..b5eb9c2ee 100644
--- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
+++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
index 05874ec2c..c22ca4d60 100644
--- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
@@ -10,7 +10,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Parsers
@@ -158,7 +158,7 @@ namespace MediaBrowser.LocalMetadata.Parsers
}
else
{
- Logger.Warn("Invalid Added value found: " + val);
+ Logger.LogWarning("Invalid Added value found: " + val);
}
}
break;
diff --git a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
index 891a3ad3f..e5b4190a4 100644
--- a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Xml;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs
index 3225603bf..0139ce917 100644
--- a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
diff --git a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs
index f9b334396..939e2d1df 100644
--- a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Parsers
diff --git a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
index 8b25dd3bd..dcf88e90e 100644
--- a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
index 30576b531..2629547f8 100644
--- a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs
index 006376b41..4ca7224ca 100644
--- a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Providers
diff --git a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs
index 3e7acc28d..0ba52f84d 100644
--- a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
index 909daf2dd..ce37adda3 100644
--- a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
+++ b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.LocalMetadata.Parsers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading;
using MediaBrowser.LocalMetadata.Savers;
diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
index 81622f54c..9666c8266 100644
--- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
@@ -20,7 +20,7 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
@@ -135,7 +135,7 @@ namespace MediaBrowser.LocalMetadata.Savers
}
catch (Exception ex)
{
- Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message);
+ Logger.LogError(ex, "Error setting hidden attribute on {path}", path);
}
}
diff --git a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
index 42a96588a..1995d8c38 100644
--- a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs
@@ -10,7 +10,7 @@ using System.Xml;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
diff --git a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs
index 109b21d35..da0d82490 100644
--- a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs
@@ -5,7 +5,7 @@ using System.Collections.Generic;
using System.IO;
using System.Xml;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
diff --git a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs
index 1a8e83e72..62d4993b3 100644
--- a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs
@@ -6,7 +6,7 @@ using System.Globalization;
using System.IO;
using System.Xml;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
diff --git a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs
index 8409e483d..a84fcd57e 100644
--- a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs
@@ -5,7 +5,7 @@ using System.Collections.Generic;
using System.IO;
using System.Xml;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
diff --git a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
index 521a0b00e..0c03bcacd 100644
--- a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs
@@ -6,7 +6,7 @@ using System.Collections.Generic;
using System.IO;
using System.Xml;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.LocalMetadata.Savers
diff --git a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs
index 566e7946d..2a874eba1 100644
--- a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using MediaBrowser.Model.Diagnostics;
diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
index 3383276bc..187f350b8 100644
--- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
@@ -105,7 +105,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
OnTranscodeBeginning(encodingJob);
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
- Logger.Info(commandLineLogMessage);
+ Logger.LogInformation(commandLineLogMessage);
var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath));
@@ -124,7 +124,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- Logger.ErrorException("Error starting ffmpeg", ex);
+ Logger.LogError(ex, "Error starting ffmpeg");
OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
@@ -150,7 +150,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
private void Cancel(IProcess process, EncodingJob job)
{
- Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
+ Logger.LogInformation("Killing ffmpeg process for {0}", job.OutputFilePath);
//process.Kill();
process.StandardInput.WriteLine("q");
@@ -167,7 +167,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
job.HasExited = true;
- Logger.Debug("Disposing stream resources");
+ Logger.LogDebug("Disposing stream resources");
job.Dispose();
var isSuccesful = false;
@@ -175,13 +175,13 @@ namespace MediaBrowser.MediaEncoding.Encoder
try
{
var exitCode = process.ExitCode;
- Logger.Info("FFMpeg exited with code {0}", exitCode);
+ Logger.LogInformation("FFMpeg exited with code {0}", exitCode);
isSuccesful = exitCode == 0;
}
- catch
+ catch (Exception ex)
{
- Logger.Error("FFMpeg exited with an error.");
+ Logger.LogError(ex, "FFMpeg exited with an error.");
}
if (isSuccesful && !job.IsCancelled)
@@ -231,7 +231,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
//}
//catch (Exception ex)
//{
- // Logger.ErrorException("Error disposing ffmpeg.", ex);
+ // Logger.LogError("Error disposing ffmpeg.", ex);
//}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index 59f3576ec..578e9f264 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Globalization;
+using System.Linq;
+using System.Text.RegularExpressions;
using MediaBrowser.Model.Diagnostics;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
@@ -18,21 +19,21 @@ namespace MediaBrowser.MediaEncoding.Encoder
_processFactory = processFactory;
}
- public Tuple<List<string>, List<string>> Validate(string encoderPath)
+ public (IEnumerable<string> decoders, IEnumerable<string> encoders) Validate(string encoderPath)
{
- _logger.Info("Validating media encoder at {0}", encoderPath);
+ _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath);
- var decoders = GetDecoders(encoderPath);
- var encoders = GetEncoders(encoderPath);
+ var decoders = GetCodecs(encoderPath, Codec.Decoder);
+ var encoders = GetCodecs(encoderPath, Codec.Encoder);
- _logger.Info("Encoder validation complete");
+ _logger.LogInformation("Encoder validation complete");
- return new Tuple<List<string>, List<string>>(decoders, encoders);
+ return (decoders, encoders);
}
public bool ValidateVersion(string encoderAppPath, bool logOutput)
{
- string output = string.Empty;
+ string output = null;
try
{
output = GetProcessOutput(encoderAppPath, "-version");
@@ -41,7 +42,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
if (logOutput)
{
- _logger.ErrorException("Error validating encoder", ex);
+ _logger.LogError(ex, "Error validating encoder");
}
}
@@ -50,7 +51,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return false;
}
- _logger.Info("ffmpeg info: {0}", output);
+ _logger.LogDebug("ffmpeg output: {Output}", output);
if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
{
@@ -71,20 +72,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return true;
}
- private List<string> GetDecoders(string encoderAppPath)
- {
- string output = string.Empty;
- try
- {
- output = GetProcessOutput(encoderAppPath, "-decoders");
- }
- catch (Exception )
- {
- //_logger.ErrorException("Error detecting available decoders", ex);
- }
-
- var found = new List<string>();
- var required = new[]
+ private static readonly string[] requiredDecoders = new[]
{
"mpeg2video",
"h264_qsv",
@@ -101,33 +89,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
"hevc"
};
- foreach (var codec in required)
- {
- var srch = " " + codec + " ";
-
- if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1)
- {
- _logger.Info("Decoder available: " + codec);
- found.Add(codec);
- }
- }
-
- return found;
- }
-
- private List<string> GetEncoders(string encoderAppPath)
- {
- string output = null;
- try
- {
- output = GetProcessOutput(encoderAppPath, "-encoders");
- }
- catch
- {
- }
-
- var found = new List<string>();
- var required = new[]
+ private static readonly string[] requiredEncoders = new[]
{
"libx264",
"libx265",
@@ -151,32 +113,46 @@ namespace MediaBrowser.MediaEncoding.Encoder
"ac3"
};
- output = output ?? string.Empty;
+ private enum Codec
+ {
+ Encoder,
+ Decoder
+ }
- var index = 0;
+ private IEnumerable<string> GetCodecs(string encoderAppPath, Codec codec)
+ {
+ string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
+ string output = null;
+ try
+ {
+ output = GetProcessOutput(encoderAppPath, "-" + codecstr);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error detecting available {Codec}", codecstr);
+ }
- foreach (var codec in required)
+ if (string.IsNullOrWhiteSpace(output))
{
- var srch = " " + codec + " ";
+ return Enumerable.Empty<string>();
+ }
- if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1)
- {
- if (index < required.Length - 1)
- {
- _logger.Info("Encoder available: " + codec);
- }
+ var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders;
- found.Add(codec);
- }
- index++;
- }
+ var found = Regex
+ .Matches(output, @"^\s\S{6}\s(?<codec>[\w|-]+)\s+.+$", RegexOptions.Multiline)
+ .Cast<Match>()
+ .Select(x => x.Groups["codec"].Value)
+ .Where(x => required.Contains(x));
+
+ _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found);
return found;
}
private string GetProcessOutput(string path, string arguments)
{
- var process = _processFactory.Create(new ProcessOptions
+ IProcess process = _processFactory.Create(new ProcessOptions
{
CreateNoWindow = true,
UseShellExecute = false,
@@ -184,10 +160,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
Arguments = arguments,
IsHidden = true,
ErrorDialog = false,
- RedirectStandardOutput = true
+ RedirectStandardOutput = true,
+ // ffmpeg uses stderr to log info, don't show this
+ RedirectStandardError = true
});
- _logger.Info("Running {0} {1}", path, arguments);
+ _logger.LogDebug("Running {Path} {Arguments}", path, arguments);
using (process)
{
@@ -199,16 +177,16 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch
{
- _logger.Info("Killing process {0} {1}", path, arguments);
+ _logger.LogWarning("Killing process {Path} {Arguments}", path, arguments);
// Hate having to do this
try
{
process.Kill();
}
- catch (Exception ex1)
+ catch (Exception ex)
{
- _logger.ErrorException("Error killing process", ex1);
+ _logger.LogError(ex, "Error killing process");
}
throw;
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
index 294181fcc..9761de98f 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
@@ -1,19 +1,11 @@
-using MediaBrowser.Controller.Library;
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Drawing;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
@@ -81,7 +73,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.ErrorException("Error disposing log stream", ex);
+ _logger.LogError(ex, "Error disposing log stream");
}
LogFileStream = null;
@@ -98,7 +90,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.ErrorException("Error closing media source", ex);
+ _logger.LogError(ex, "Error closing media source");
}
}
}
@@ -153,7 +145,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
- // job.Framerate = framerate;
+ //job.Framerate = framerate;
if (!percentComplete.HasValue && ticks.HasValue && RunTimeTicks.HasValue)
{
@@ -166,8 +158,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
Progress.Report(percentComplete.Value);
}
- // job.TranscodingPositionTicks = ticks;
- // job.BytesTranscoded = bytesTranscoded;
+ /*
+ job.TranscodingPositionTicks = ticks;
+ job.BytesTranscoded = bytesTranscoded;
var deviceId = Options.DeviceId;
@@ -176,21 +169,21 @@ namespace MediaBrowser.MediaEncoding.Encoder
var audioCodec = ActualOutputVideoCodec;
var videoCodec = ActualOutputVideoCodec;
- // SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
- // {
- // Bitrate = job.TotalOutputBitrate,
- // AudioCodec = audioCodec,
- // VideoCodec = videoCodec,
- // Container = job.Options.OutputContainer,
- // Framerate = framerate,
- // CompletionPercentage = percentComplete,
- // Width = job.OutputWidth,
- // Height = job.OutputHeight,
- // AudioChannels = job.OutputAudioChannels,
- // IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
- // IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
- // });
- }
+ SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
+ {
+ Bitrate = job.TotalOutputBitrate,
+ AudioCodec = audioCodec,
+ VideoCodec = videoCodec,
+ Container = job.Options.OutputContainer,
+ Framerate = framerate,
+ CompletionPercentage = percentComplete,
+ Width = job.OutputWidth,
+ Height = job.OutputHeight,
+ AudioChannels = job.OutputAudioChannels,
+ IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
+ IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
+ });
+ }*/
}
}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs
index 8d8d05a16..4e6ee89e1 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs
deleted file mode 100644
index e21292cbd..000000000
--- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs
+++ /dev/null
@@ -1,182 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Common.Configuration;
-
-using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Net;
-
-namespace MediaBrowser.MediaEncoding.Encoder
-{
- public class FontConfigLoader
- {
- private readonly IHttpClient _httpClient;
- private readonly IApplicationPaths _appPaths;
- private readonly ILogger _logger;
- private readonly IZipClient _zipClient;
- private readonly IFileSystem _fileSystem;
-
- private readonly string[] _fontUrls =
- {
- "https://github.com/MediaBrowser/MediaBrowser.Resources/raw/master/ffmpeg/ARIALUNI.7z"
- };
-
- public FontConfigLoader(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, IZipClient zipClient, IFileSystem fileSystem)
- {
- _httpClient = httpClient;
- _appPaths = appPaths;
- _logger = logger;
- _zipClient = zipClient;
- _fileSystem = fileSystem;
- }
-
- /// <summary>
- /// Extracts the fonts.
- /// </summary>
- /// <param name="targetPath">The target path.</param>
- /// <returns>Task.</returns>
- public async Task DownloadFonts(string targetPath)
- {
- try
- {
- var fontsDirectory = Path.Combine(targetPath, "fonts");
-
- _fileSystem.CreateDirectory(fontsDirectory);
-
- const string fontFilename = "ARIALUNI.TTF";
-
- var fontFile = Path.Combine(fontsDirectory, fontFilename);
-
- if (_fileSystem.FileExists(fontFile))
- {
- await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
- }
- else
- {
- // Kick this off, but no need to wait on it
- var task = Task.Run(async () =>
- {
- await DownloadFontFile(fontsDirectory, fontFilename, new SimpleProgress<double>()).ConfigureAwait(false);
-
- await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
- });
- }
- }
- catch (HttpException ex)
- {
- // Don't let the server crash because of this
- _logger.ErrorException("Error downloading ffmpeg font files", ex);
- }
- catch (Exception ex)
- {
- // Don't let the server crash because of this
- _logger.ErrorException("Error writing ffmpeg font files", ex);
- }
- }
-
- /// <summary>
- /// Downloads the font file.
- /// </summary>
- /// <param name="fontsDirectory">The fonts directory.</param>
- /// <param name="fontFilename">The font filename.</param>
- /// <returns>Task.</returns>
- private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
- {
- var existingFile = _fileSystem
- .GetFilePaths(_appPaths.ProgramDataPath, true)
- .FirstOrDefault(i => string.Equals(fontFilename, Path.GetFileName(i), StringComparison.OrdinalIgnoreCase));
-
- if (existingFile != null)
- {
- try
- {
- _fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
- return;
- }
- catch (IOException ex)
- {
- // Log this, but don't let it fail the operation
- _logger.ErrorException("Error copying file", ex);
- }
- }
-
- string tempFile = null;
-
- foreach (var url in _fontUrls)
- {
- progress.Report(0);
-
- try
- {
- tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
- {
- Url = url,
- Progress = progress
-
- }).ConfigureAwait(false);
-
- break;
- }
- catch (Exception ex)
- {
- // The core can function without the font file, so handle this
- _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
- }
- }
-
- if (string.IsNullOrEmpty(tempFile))
- {
- return;
- }
-
- Extract7zArchive(tempFile, fontsDirectory);
-
- try
- {
- _fileSystem.DeleteFile(tempFile);
- }
- catch (IOException ex)
- {
- // Log this, but don't let it fail the operation
- _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
- }
- }
- private void Extract7zArchive(string archivePath, string targetPath)
- {
- _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
-
- _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
- }
-
- /// <summary>
- /// Writes the font config file.
- /// </summary>
- /// <param name="fontsDirectory">The fonts directory.</param>
- /// <returns>Task.</returns>
- private async Task WriteFontConfigFile(string fontsDirectory)
- {
- const string fontConfigFilename = "fonts.conf";
- var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
-
- if (!_fileSystem.FileExists(fontConfigFile))
- {
- var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
-
- var bytes = Encoding.UTF8.GetBytes(contents);
-
- using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileOpenMode.Create, FileAccessMode.Write,
- FileShareMode.Read, true))
- {
- await fileStream.WriteAsync(bytes, 0, bytes.Length);
- }
- }
- }
- }
-}
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index 64372c072..a93dd9742 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -6,10 +6,8 @@ using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Session;
using MediaBrowser.MediaEncoding.Probing;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -25,6 +23,7 @@ using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
@@ -71,13 +70,27 @@ namespace MediaBrowser.MediaEncoding.Encoder
private readonly string _originalFFMpegPath;
private readonly string _originalFFProbePath;
private readonly int DefaultImageExtractionTimeoutMs;
- private readonly bool EnableEncoderFontFile;
-
private readonly IEnvironmentInfo _environmentInfo;
- public MediaEncoder(ILogger logger, IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, bool hasExternalEncoder, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILiveTvManager liveTvManager, IIsoManager isoManager, ILibraryManager libraryManager, IChannelManager channelManager, ISessionManager sessionManager, Func<ISubtitleEncoder> subtitleEncoder, Func<IMediaSourceManager> mediaSourceManager, IHttpClient httpClient, IZipClient zipClient, IProcessFactory processFactory,
+ public MediaEncoder(ILogger logger,
+ IJsonSerializer jsonSerializer,
+ string ffMpegPath,
+ string ffProbePath,
+ bool hasExternalEncoder,
+ IServerConfigurationManager configurationManager,
+ IFileSystem fileSystem,
+ ILiveTvManager liveTvManager,
+ IIsoManager isoManager,
+ ILibraryManager libraryManager,
+ IChannelManager channelManager,
+ ISessionManager sessionManager,
+ Func<ISubtitleEncoder> subtitleEncoder,
+ Func<IMediaSourceManager> mediaSourceManager,
+ IHttpClient httpClient,
+ IZipClient zipClient,
+ IProcessFactory processFactory,
int defaultImageExtractionTimeoutMs,
- bool enableEncoderFontFile, IEnvironmentInfo environmentInfo)
+ IEnvironmentInfo environmentInfo)
{
_logger = logger;
_jsonSerializer = jsonSerializer;
@@ -94,7 +107,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
_zipClient = zipClient;
_processFactory = processFactory;
DefaultImageExtractionTimeoutMs = defaultImageExtractionTimeoutMs;
- EnableEncoderFontFile = enableEncoderFontFile;
_environmentInfo = environmentInfo;
FFProbePath = ffProbePath;
FFMpegPath = ffMpegPath;
@@ -102,8 +114,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
_originalFFMpegPath = ffMpegPath;
_hasExternalEncoder = hasExternalEncoder;
-
- SetEnvironmentVariable();
}
private readonly object _logLock = new object();
@@ -117,7 +127,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.ErrorException("Error setting FFREPORT environment variable", ex);
+ _logger.LogError(ex, "Error setting FFREPORT environment variable");
}
}
}
@@ -132,31 +142,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- //_logger.ErrorException("Error setting FFREPORT environment variable", ex);
+ _logger.LogError(ex, "Error setting FFREPORT environment variable");
}
}
}
- private void SetEnvironmentVariable()
- {
- try
- {
- //_environmentInfo.SetProcessEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32");
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error setting FFREPORT environment variable", ex);
- }
- try
- {
- //_environmentInfo.SetUserEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32");
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error setting FFREPORT environment variable", ex);
- }
- }
-
public string EncoderLocationType
{
get
@@ -198,18 +188,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
var result = new EncoderValidator(_logger, _processFactory).Validate(FFMpegPath);
- SetAvailableDecoders(result.Item1);
- SetAvailableEncoders(result.Item2);
-
- if (EnableEncoderFontFile)
- {
- var directory = FileSystem.GetDirectoryName(FFMpegPath);
-
- if (!string.IsNullOrWhiteSpace(directory) && FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.ProgramDataPath, directory))
- {
- new FontConfigLoader(_httpClient, ConfigurationManager.ApplicationPaths, _logger, _zipClient, FileSystem).DownloadFonts(directory).ConfigureAwait(false);
- }
- }
+ SetAvailableDecoders(result.decoders);
+ SetAvailableEncoders(result.encoders);
}
}
@@ -252,7 +232,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return;
}
- _logger.Info("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty);
+ _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty);
Tuple<string, string> newPaths;
@@ -414,8 +394,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
private void LogPaths()
{
- _logger.Info("FFMpeg: {0}", FFMpegPath ?? "not found");
- _logger.Info("FFProbe: {0}", FFProbePath ?? "not found");
+ _logger.LogInformation("FFMpeg: {0}", FFMpegPath ?? "not found");
+ _logger.LogInformation("FFProbe: {0}", FFProbePath ?? "not found");
}
private EncodingOptions GetEncodingOptions()
@@ -424,14 +404,14 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
private List<string> _encoders = new List<string>();
- public void SetAvailableEncoders(List<string> list)
+ public void SetAvailableEncoders(IEnumerable<string> list)
{
_encoders = list.ToList();
//_logger.Info("Supported encoders: {0}", string.Join(",", list.ToArray()));
}
private List<string> _decoders = new List<string>();
- public void SetAvailableDecoders(List<string> list)
+ public void SetAvailableDecoders(IEnumerable<string> list)
{
_decoders = list.ToList();
//_logger.Info("Supported decoders: {0}", string.Join(",", list.ToArray()));
@@ -557,11 +537,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (forceEnableLogging)
{
- _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
}
else
{
- _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
}
using (var processWrapper = new ProcessWrapper(process, this, _logger))
@@ -572,7 +552,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
//process.BeginErrorReadLine();
- var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
+ var result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
if (result == null || (result.streams == null && result.format == null))
{
@@ -649,9 +629,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
throw;
}
- catch
+ catch (Exception ex)
{
- _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
+ _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument);
}
}
@@ -755,7 +735,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
ErrorDialog = false
});
- _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
using (var processWrapper = new ProcessWrapper(process, this, _logger))
{
@@ -783,7 +763,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
- _logger.Error(msg);
+ _logger.LogError(msg);
throw new Exception(msg);
}
@@ -877,7 +857,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
ErrorDialog = false
});
- _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
+ _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -929,7 +909,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
- _logger.Error(msg);
+ _logger.LogError(msg);
throw new Exception(msg);
}
@@ -961,7 +941,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
IProgress<double> progress,
CancellationToken cancellationToken)
{
- _logger.Error("EncodeVideo");
+ _logger.LogError("EncodeVideo");
var job = await new VideoEncoder(this,
_logger,
ConfigurationManager,
@@ -999,18 +979,18 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.Error("Error in WaitForExit", ex);
+ _logger.LogError(ex, "Error in WaitForExit");
}
try
{
- _logger.Info("Killing ffmpeg process");
+ _logger.LogInformation("Killing ffmpeg process");
process.Process.Kill();
}
catch (Exception ex)
{
- _logger.ErrorException("Error killing process", ex);
+ _logger.LogError(ex, "Error killing process");
}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs
index 96c126923..732b5bf84 100644
--- a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading.Tasks;
@@ -63,4 +63,4 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
index d9d2b4bf9..d93394957 100644
--- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
+++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
@@ -6,7 +6,7 @@
</PropertyGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<ItemGroup>
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 0a3532b8c..5367a87f7 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -1,20 +1,17 @@
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
-using MediaBrowser.Model.IO;
-
-using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Probing
{
@@ -1351,11 +1348,11 @@ namespace MediaBrowser.MediaEncoding.Probing
{
video.Timestamp = GetMpegTimestamp(video.Path);
- _logger.Debug("Video has {0} timestamp", video.Timestamp);
+ _logger.LogDebug("Video has {timestamp} timestamp", video.Timestamp);
}
catch (Exception ex)
{
- _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
+ _logger.LogError(ex, "Error extracting timestamp info from {path}", video.Path);
video.Timestamp = null;
}
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
index 3954897ca..2d29f29e3 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
@@ -15,9 +15,9 @@ using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
using OpenSubtitlesHandler;
namespace MediaBrowser.MediaEncoding.Subtitles
@@ -34,9 +34,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
private readonly IJsonSerializer _json;
private readonly IFileSystem _fileSystem;
- public OpenSubtitleDownloader(ILogManager logManager, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem)
+ public OpenSubtitleDownloader(ILoggerFactory loggerFactory, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem)
{
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
_httpClient = httpClient;
_config = config;
_encryption = encryption;
@@ -208,7 +208,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var result = OpenSubtitles.GetSubLanguages("en");
if (!(result is MethodResponseGetSubLanguages))
{
- _logger.Error("Invalid response type");
+ _logger.LogError("Invalid response type");
return new List<NameIdPair>();
}
@@ -243,19 +243,19 @@ namespace MediaBrowser.MediaEncoding.Subtitles
case VideoContentType.Episode:
if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName))
{
- _logger.Debug("Episode information missing");
+ _logger.LogDebug("Episode information missing");
return new List<RemoteSubtitleInfo>();
}
break;
case VideoContentType.Movie:
if (string.IsNullOrEmpty(request.Name))
{
- _logger.Debug("Movie name missing");
+ _logger.LogDebug("Movie name missing");
return new List<RemoteSubtitleInfo>();
}
if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId))
{
- _logger.Debug("Imdb id missing");
+ _logger.LogDebug("Imdb id missing");
return new List<RemoteSubtitleInfo>();
}
break;
@@ -263,7 +263,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (string.IsNullOrEmpty(request.MediaPath))
{
- _logger.Debug("Path Missing");
+ _logger.LogDebug("Path Missing");
return new List<RemoteSubtitleInfo>();
}
@@ -300,7 +300,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false);
if (!(result is MethodResponseSubtitleSearch))
{
- _logger.Error("Invalid response type");
+ _logger.LogError("Invalid response type");
return new List<RemoteSubtitleInfo>();
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
index de6d7bc72..7ca8aa1fd 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -50,7 +50,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
// This occurs when subtitle text has an empty line as part of the text.
// Need to adjust the break statement below to resolve this.
- _logger.Warn("Unrecognized line in srt: {0}", line);
+ _logger.LogWarning("Unrecognized line in srt: {0}", line);
continue;
}
subEvent.StartPositionTicks = GetTicks(time[0]);
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
index d565ff3e2..68faffa91 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
@@ -1,26 +1,25 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Serialization;
-using System;
+using System;
using System.Collections.Concurrent;
-using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Text;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Subtitles
{
@@ -37,7 +36,17 @@ namespace MediaBrowser.MediaEncoding.Subtitles
private readonly IProcessFactory _processFactory;
private readonly ITextEncoding _textEncoding;
- public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager, IProcessFactory processFactory, ITextEncoding textEncoding)
+ public SubtitleEncoder(
+ ILibraryManager libraryManager,
+ ILogger logger,
+ IApplicationPaths appPaths,
+ IFileSystem fileSystem,
+ IMediaEncoder mediaEncoder,
+ IJsonSerializer json,
+ IHttpClient httpClient,
+ IMediaSourceManager mediaSourceManager,
+ IProcessFactory processFactory,
+ ITextEncoding textEncoding)
{
_libraryManager = libraryManager;
_logger = logger;
@@ -46,6 +55,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
_mediaEncoder = mediaEncoder;
_json = json;
_httpClient = httpClient;
+ _mediaSourceManager = mediaSourceManager;
_processFactory = processFactory;
_textEncoding = textEncoding;
}
@@ -99,7 +109,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (endTimeTicks.HasValue)
{
- var endTime = endTimeTicks.Value;
+ long endTime = endTimeTicks.Value;
track.TrackEvents = track.TrackEvents
.TakeWhile(i => i.StartPositionTicks <= endTime)
@@ -139,48 +149,51 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
.ConfigureAwait(false);
- var inputFormat = subtitle.Item2;
+ var inputFormat = subtitle.format;
var writer = TryGetWriter(outputFormat);
// Return the original if we don't have any way of converting it
if (writer == null)
{
- return subtitle.Item1;
+ return subtitle.stream;
}
// Return the original if the same format is being requested
// Character encoding was already handled in GetSubtitleStream
if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
{
- return subtitle.Item1;
+ return subtitle.stream;
}
- using (var stream = subtitle.Item1)
+ using (var stream = subtitle.stream)
{
- return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
+ return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
}
}
- private async Task<Tuple<Stream, string>> GetSubtitleStream(MediaSourceInfo mediaSource,
+ private async Task<(Stream stream, string format)> GetSubtitleStream(
+ MediaSourceInfo mediaSource,
MediaStream subtitleStream,
CancellationToken cancellationToken)
{
- var inputFiles = new[] { mediaSource.Path };
+ string[] inputFiles;
- if (mediaSource.VideoType.HasValue)
+ if (mediaSource.VideoType.HasValue
+ && (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd))
{
- if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
- {
- var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
- inputFiles = mediaSourceItem.GetPlayableStreamFileNames(_mediaEncoder).ToArray();
- }
+ var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
+ inputFiles = mediaSourceItem.GetPlayableStreamFileNames(_mediaEncoder);
+ }
+ else
+ {
+ inputFiles = new[] { mediaSource.Path };
}
var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
- var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
+ var stream = await GetSubtitleStream(fileInfo.Path, subtitleStream.Language, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false);
- return new Tuple<Stream, string>(stream, fileInfo.Item3);
+ return (stream, fileInfo.Format);
}
private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
@@ -190,20 +203,18 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true);
- _logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
+ _logger.LogDebug("charset {0} detected for {1}", charset ?? "null", path);
if (!string.IsNullOrEmpty(charset))
{
using (var inputStream = new MemoryStream(bytes))
+ using (var reader = new StreamReader(inputStream, _textEncoding.GetEncodingFromCharset(charset)))
{
- using (var reader = new StreamReader(inputStream, _textEncoding.GetEncodingFromCharset(charset)))
- {
- var text = await reader.ReadToEndAsync().ConfigureAwait(false);
+ var text = await reader.ReadToEndAsync().ConfigureAwait(false);
- bytes = Encoding.UTF8.GetBytes(text);
+ bytes = Encoding.UTF8.GetBytes(text);
- return new MemoryStream(bytes);
- }
+ return new MemoryStream(bytes);
}
}
}
@@ -211,7 +222,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles
return _fileSystem.OpenRead(path);
}
- private async Task<Tuple<string, MediaProtocol, string, bool>> GetReadableFile(string mediaPath,
+ private async Task<SubtitleInfo> GetReadableFile(
+ string mediaPath,
string[] inputFiles,
MediaProtocol protocol,
MediaStream subtitleStream,
@@ -226,30 +238,30 @@ namespace MediaBrowser.MediaEncoding.Subtitles
string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
{
- // Extract
+ // Extract
outputCodec = "copy";
outputFormat = subtitleStream.Codec;
}
else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
{
- // Extract
+ // Extract
outputCodec = "copy";
outputFormat = "srt";
}
else
{
- // Extract
+ // Extract
outputCodec = "srt";
outputFormat = "srt";
}
- // Extract
+ // Extract
var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
.ConfigureAwait(false);
- return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, outputFormat, false);
+ return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
}
var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
@@ -257,15 +269,31 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (GetReader(currentFormat, false) == null)
{
- // Convert
+ // Convert
var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
- return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, "srt", true);
+ return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
+ }
+
+ return new SubtitleInfo(subtitleStream.Path, protocol, currentFormat, true);
+ }
+
+ private struct SubtitleInfo
+ {
+ public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
+ {
+ Path = path;
+ Protocol = protocol;
+ Format = format;
+ IsExternal = isExternal;
}
- return new Tuple<string, MediaProtocol, string, bool>(subtitleStream.Path, protocol, currentFormat, true);
+ public string Path { get; set; }
+ public MediaProtocol Protocol { get; set; }
+ public string Format { get; set; }
+ public bool IsExternal { get; set; }
}
private ISubtitleParser GetReader(string format, bool throwIfMissing)
@@ -423,7 +451,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
ErrorDialog = false
});
- _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
try
{
@@ -431,7 +459,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
catch (Exception ex)
{
- _logger.ErrorException("Error starting ffmpeg", ex);
+ _logger.LogError(ex, "Error starting ffmpeg");
throw;
}
@@ -442,13 +470,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
try
{
- _logger.Info("Killing ffmpeg subtitle conversion process");
+ _logger.LogInformation("Killing ffmpeg subtitle conversion process");
process.Kill();
}
catch (Exception ex)
{
- _logger.ErrorException("Error killing subtitle conversion process", ex);
+ _logger.LogError(ex, "Error killing subtitle conversion process");
}
}
@@ -466,12 +494,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
try
{
- _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
+ _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
_fileSystem.DeleteFile(outputPath);
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
+ _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
}
}
}
@@ -482,15 +510,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (failed)
{
- var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);
+ var msg = string.Format("ffmpeg subtitle conversion failed for {Path}", inputPath);
- _logger.Error(msg);
+ _logger.LogError(msg);
throw new Exception(msg);
}
await SetAssFont(outputPath).ConfigureAwait(false);
- _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath);
+ _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
}
/// <summary>
@@ -504,8 +532,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
- private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
- string outputCodec, string outputPath, CancellationToken cancellationToken)
+ private async Task ExtractTextSubtitle(
+ string[] inputFiles,
+ MediaProtocol protocol,
+ int subtitleStreamIndex,
+ string outputCodec,
+ string outputPath,
+ CancellationToken cancellationToken)
{
var semaphore = GetLock(outputPath);
@@ -524,8 +557,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
}
- private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
- string outputCodec, string outputPath, CancellationToken cancellationToken)
+ private async Task ExtractTextSubtitleInternal(
+ string inputPath,
+ int subtitleStreamIndex,
+ string outputCodec,
+ string outputPath,
+ CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(inputPath))
{
@@ -553,7 +590,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
ErrorDialog = false
});
- _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
try
{
@@ -561,7 +598,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
catch (Exception ex)
{
- _logger.ErrorException("Error starting ffmpeg", ex);
+ _logger.LogError(ex, "Error starting ffmpeg");
throw;
}
@@ -572,13 +609,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
try
{
- _logger.Info("Killing ffmpeg subtitle extraction process");
+ _logger.LogWarning("Killing ffmpeg subtitle extraction process");
process.Kill();
}
catch (Exception ex)
{
- _logger.ErrorException("Error killing subtitle extraction process", ex);
+ _logger.LogError(ex, "Error killing subtitle extraction process");
}
}
@@ -594,7 +631,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try
{
- _logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath);
+ _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
_fileSystem.DeleteFile(outputPath);
}
catch (FileNotFoundException)
@@ -603,7 +640,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
catch (IOException ex)
{
- _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
+ _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
}
}
else if (!_fileSystem.FileExists(outputPath))
@@ -613,17 +650,17 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (failed)
{
- var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
+ var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
- _logger.Error(msg);
+ _logger.LogError(msg);
throw new Exception(msg);
}
else
{
- var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
+ var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
- _logger.Info(msg);
+ _logger.LogInformation(msg);
}
if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
@@ -639,19 +676,17 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// <returns>Task.</returns>
private async Task SetAssFont(string file)
{
- _logger.Info("Setting ass font within {0}", file);
+ _logger.LogInformation("Setting ass font within {File}", file);
string text;
Encoding encoding;
using (var fileStream = _fileSystem.OpenRead(file))
+ using (var reader = new StreamReader(fileStream, true))
{
- using (var reader = new StreamReader(fileStream, true))
- {
- encoding = reader.CurrentEncoding;
+ encoding = reader.CurrentEncoding;
- text = await reader.ReadToEndAsync().ConfigureAwait(false);
- }
+ text = await reader.ReadToEndAsync().ConfigureAwait(false);
}
var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
@@ -659,11 +694,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
if (!string.Equals(text, newText))
{
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+ using (var writer = new StreamWriter(fileStream, encoding))
{
- using (var writer = new StreamWriter(fileStream, encoding))
- {
- writer.Write(newText);
- }
+ writer.Write(newText);
}
}
}
@@ -698,7 +731,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true);
- _logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
+ _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
return charset;
}
@@ -707,18 +740,18 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
if (protocol == MediaProtocol.Http)
{
- HttpRequestOptions opts = new HttpRequestOptions();
- opts.Url = path;
- opts.CancellationToken = cancellationToken;
+ HttpRequestOptions opts = new HttpRequestOptions()
+ {
+ Url = path,
+ CancellationToken = cancellationToken
+ };
using (var file = await _httpClient.Get(opts).ConfigureAwait(false))
+ using (var memoryStream = new MemoryStream())
{
- using (var memoryStream = new MemoryStream())
- {
- await file.CopyToAsync(memoryStream).ConfigureAwait(false);
- memoryStream.Position = 0;
+ await file.CopyToAsync(memoryStream).ConfigureAwait(false);
+ memoryStream.Position = 0;
- return memoryStream.ToArray();
- }
+ return memoryStream.ToArray();
}
}
if (protocol == MediaProtocol.File)
@@ -728,6 +761,5 @@ namespace MediaBrowser.MediaEncoding.Subtitles
throw new ArgumentOutOfRangeException("protocol");
}
-
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Activity/ActivityLogEntry.cs b/MediaBrowser.Model/Activity/ActivityLogEntry.cs
index 1f4bff10d..a61ebc268 100644
--- a/MediaBrowser.Model/Activity/ActivityLogEntry.cs
+++ b/MediaBrowser.Model/Activity/ActivityLogEntry.cs
@@ -1,4 +1,4 @@
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
namespace MediaBrowser.Model.Activity
@@ -63,6 +63,6 @@ namespace MediaBrowser.Model.Activity
/// Gets or sets the log severity.
/// </summary>
/// <value>The log severity.</value>
- public LogSeverity Severity { get; set; }
+ public LogLevel Severity { get; set; }
}
}
diff --git a/MediaBrowser.Model/Channels/ChannelFeatures.cs b/MediaBrowser.Model/Channels/ChannelFeatures.cs
index 39b40cabc..d4caf499b 100644
--- a/MediaBrowser.Model/Channels/ChannelFeatures.cs
+++ b/MediaBrowser.Model/Channels/ChannelFeatures.cs
@@ -1,4 +1,4 @@
-using System.Collections.Generic;
+using System;
namespace MediaBrowser.Model.Channels
{
@@ -76,10 +76,9 @@ namespace MediaBrowser.Model.Channels
public ChannelFeatures()
{
- MediaTypes = new ChannelMediaType[] { };
- ContentTypes = new ChannelMediaContentType[] { };
-
- DefaultSortFields = new ChannelItemSortField[] { };
+ MediaTypes = Array.Empty<ChannelMediaType>();
+ ContentTypes = Array.Empty<ChannelMediaContentType>();
+ DefaultSortFields = Array.Empty<ChannelItemSortField>();
}
}
}
diff --git a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
index b5b0101cb..08bf2379f 100644
--- a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs
@@ -9,6 +9,7 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
public class BaseApplicationConfiguration
{
+ // TODO: @bond Remove?
/// <summary>
/// Gets or sets a value indicating whether [enable debug level logging].
/// </summary>
@@ -21,6 +22,7 @@ namespace MediaBrowser.Model.Configuration
/// <value><c>true</c> if [enable auto update]; otherwise, <c>false</c>.</value>
public bool EnableAutoUpdate { get; set; }
+ // TODO: @bond Remove?
/// <summary>
/// The number of days we should retain log files
/// </summary>
@@ -28,12 +30,6 @@ namespace MediaBrowser.Model.Configuration
public int LogFileRetentionDays { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether [run at startup].
- /// </summary>
- /// <value><c>true</c> if [run at startup]; otherwise, <c>false</c>.</value>
- public bool RunAtStartup { get; set; }
-
- /// <summary>
/// Gets or sets a value indicating whether this instance is first run.
/// </summary>
/// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs
index a271d43af..cc70cc888 100644
--- a/MediaBrowser.Model/Configuration/LibraryOptions.cs
+++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs
@@ -6,7 +6,6 @@ namespace MediaBrowser.Model.Configuration
{
public class LibraryOptions
{
- public bool EnableArchiveMediaFiles { get; set; }
public bool EnablePhotos { get; set; }
public bool EnableRealtimeMonitor { get; set; }
public bool EnableChapterImageExtraction { get; set; }
@@ -65,10 +64,10 @@ namespace MediaBrowser.Model.Configuration
public LibraryOptions()
{
- TypeOptions = new TypeOptions[] { };
- DisabledSubtitleFetchers = new string[] { };
- SubtitleFetcherOrder = new string[] { };
- DisabledLocalMetadataReaders = new string[] { };
+ TypeOptions = Array.Empty<TypeOptions>();
+ DisabledSubtitleFetchers = Array.Empty<string>();
+ SubtitleFetcherOrder = Array.Empty<string>();
+ DisabledLocalMetadataReaders = Array.Empty<string>();
SkipSubtitlesIfAudioTrackMatches = true;
RequirePerfectSubtitleMatch = true;
@@ -76,7 +75,7 @@ namespace MediaBrowser.Model.Configuration
EnablePhotos = true;
SaveSubtitlesWithMedia = true;
EnableRealtimeMonitor = true;
- PathInfos = new MediaPathInfo[] { };
+ PathInfos = Array.Empty<MediaPathInfo>();
EnableInternetProviders = true;
EnableAutomaticSeriesGrouping = true;
SeasonZeroDisplayName = "Specials";
@@ -141,11 +140,11 @@ namespace MediaBrowser.Model.Configuration
public TypeOptions()
{
- MetadataFetchers = new string[] { };
- MetadataFetcherOrder = new string[] { };
- ImageFetchers = new string[] { };
- ImageFetcherOrder = new string[] { };
- ImageOptions = new ImageOption[] { };
+ MetadataFetchers = Array.Empty<string>();
+ MetadataFetcherOrder = Array.Empty<string>();
+ ImageFetchers = Array.Empty<string>();
+ ImageFetcherOrder = Array.Empty<string>();
+ ImageOptions = Array.Empty<ImageOption>();
}
public static Dictionary<string, ImageOption[]> DefaultImageOptions = new Dictionary<string, ImageOption[]>
diff --git a/MediaBrowser.Model/Configuration/MetadataOptions.cs b/MediaBrowser.Model/Configuration/MetadataOptions.cs
index 26cfee085..dde2bd090 100644
--- a/MediaBrowser.Model/Configuration/MetadataOptions.cs
+++ b/MediaBrowser.Model/Configuration/MetadataOptions.cs
@@ -1,5 +1,4 @@
-using MediaBrowser.Model.Extensions;
-using System;
+using System;
namespace MediaBrowser.Model.Configuration
{
@@ -21,18 +20,12 @@ namespace MediaBrowser.Model.Configuration
public MetadataOptions()
{
- DisabledMetadataSavers = new string[] { };
- LocalMetadataReaderOrder = new string[] { };
-
- DisabledMetadataFetchers = new string[] { };
- MetadataFetcherOrder = new string[] { };
- DisabledImageFetchers = new string[] { };
- ImageFetcherOrder = new string[] { };
- }
-
- public bool IsMetadataSaverEnabled(string name)
- {
- return !ListHelper.ContainsIgnoreCase(DisabledMetadataSavers, name);
+ DisabledMetadataSavers = Array.Empty<string>();
+ LocalMetadataReaderOrder = Array.Empty<string>();
+ DisabledMetadataFetchers = Array.Empty<string>();
+ MetadataFetcherOrder = Array.Empty<string>();
+ DisabledImageFetchers = Array.Empty<string>();
+ ImageFetcherOrder = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
index 80142cf43..0bd20f837 100644
--- a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
+++ b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs
@@ -1,4 +1,4 @@
-using System.Collections.Generic;
+using System;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Model.Configuration
@@ -25,8 +25,8 @@ namespace MediaBrowser.Model.Configuration
public MetadataPluginSummary()
{
- SupportedImageTypes = new ImageType[] { };
- Plugins = new MetadataPlugin[] { };
+ SupportedImageTypes = Array.Empty<ImageType>();
+ Plugins = Array.Empty<MetadataPlugin>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
index cc1275035..565d5f74b 100644
--- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
@@ -173,9 +173,6 @@ namespace MediaBrowser.Model.Configuration
public int RemoteClientBitrateLimit { get; set; }
- public int SchemaVersion { get; set; }
-
- public bool EnableAnonymousUsageReporting { get; set; }
public bool EnableFolderView { get; set; }
public bool EnableGroupingIntoCollections { get; set; }
public bool DisplaySpecialsWithinSeasons { get; set; }
@@ -202,13 +199,13 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
public ServerConfiguration()
{
- UninstalledPlugins = new string[] { };
- RemoteIPFilter = new string[] { };
- LocalNetworkSubnets = new string[] { };
- LocalNetworkAddresses = new string[] { };
- CodecsUsed = new string[] { };
+ UninstalledPlugins = Array.Empty<string>();
+ RemoteIPFilter = Array.Empty<string>();
+ LocalNetworkSubnets = Array.Empty<string>();
+ LocalNetworkAddresses = Array.Empty<string>();
+ CodecsUsed = Array.Empty<string>();
ImageExtractionTimeoutMs = 0;
- PathSubstitutions = new PathSubstitution[] { };
+ PathSubstitutions = Array.Empty<PathSubstitution>();
EnableSimpleArtistDetection = true;
DisplaySpecialsWithinSeasons = true;
@@ -221,7 +218,6 @@ namespace MediaBrowser.Model.Configuration
HttpsPortNumber = DefaultHttpsPort;
EnableHttps = true;
EnableDashboardResponseCaching = true;
- EnableAnonymousUsageReporting = true;
EnableCaseSensitiveItemIds = true;
EnableAutomaticRestart = true;
@@ -237,7 +233,7 @@ namespace MediaBrowser.Model.Configuration
LibraryMonitorDelay = 60;
- ContentTypes = new NameValuePair[] { };
+ ContentTypes = Array.Empty<NameValuePair>();
PreferredMetadataLanguage = "en";
MetadataCountryCode = "US";
@@ -250,56 +246,51 @@ namespace MediaBrowser.Model.Configuration
MetadataOptions = new[]
{
- new MetadataOptions {ItemType = "Book"},
-
- new MetadataOptions
+ new MetadataOptions()
+ {
+ ItemType = "Book"
+ },
+ new MetadataOptions()
{
ItemType = "Movie"
},
-
new MetadataOptions
{
ItemType = "MusicVideo",
- DisabledMetadataFetchers = new []{ "The Open Movie Database" },
- DisabledImageFetchers = new []{ "The Open Movie Database", "FanArt" }
+ DisabledMetadataFetchers = new [] { "The Open Movie Database" },
+ DisabledImageFetchers = new [] { "The Open Movie Database", "FanArt" }
},
-
new MetadataOptions
{
ItemType = "Series",
- DisabledMetadataFetchers = new []{ "TheMovieDb" },
- DisabledImageFetchers = new []{ "TheMovieDb" }
+ DisabledMetadataFetchers = new [] { "TheMovieDb" },
+ DisabledImageFetchers = new [] { "TheMovieDb" }
},
-
new MetadataOptions
{
ItemType = "MusicAlbum",
- DisabledMetadataFetchers = new []{ "TheAudioDB" }
+ DisabledMetadataFetchers = new [] { "TheAudioDB" }
},
-
new MetadataOptions
{
ItemType = "MusicArtist",
- DisabledMetadataFetchers = new []{ "TheAudioDB" }
+ DisabledMetadataFetchers = new [] { "TheAudioDB" }
},
-
new MetadataOptions
{
ItemType = "BoxSet"
},
-
new MetadataOptions
{
ItemType = "Season",
- DisabledMetadataFetchers = new []{ "TheMovieDb" },
+ DisabledMetadataFetchers = new [] { "TheMovieDb" },
DisabledImageFetchers = new [] { "FanArt" }
},
-
new MetadataOptions
{
ItemType = "Episode",
- DisabledMetadataFetchers = new []{ "The Open Movie Database", "TheMovieDb" },
- DisabledImageFetchers = new []{ "The Open Movie Database", "TheMovieDb" }
+ DisabledMetadataFetchers = new [] { "The Open Movie Database", "TheMovieDb" },
+ DisabledImageFetchers = new [] { "The Open Movie Database", "TheMovieDb" }
}
};
}
diff --git a/MediaBrowser.Model/Configuration/UserConfiguration.cs b/MediaBrowser.Model/Configuration/UserConfiguration.cs
index 34b0be095..39b956138 100644
--- a/MediaBrowser.Model/Configuration/UserConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/UserConfiguration.cs
@@ -57,10 +57,10 @@ namespace MediaBrowser.Model.Configuration
HidePlayedInLatest = true;
PlayDefaultAudioTrack = true;
- LatestItemsExcludes = new string[] {};
- OrderedViews = new string[] {};
- MyMediaExcludes = new string[] {};
- GroupedFolders = new string[] {};
+ LatestItemsExcludes = Array.Empty<string>();
+ OrderedViews = Array.Empty<string>();
+ MyMediaExcludes = Array.Empty<string>();
+ GroupedFolders = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Connect/ConnectAuthenticationExchangeResult.cs b/MediaBrowser.Model/Connect/ConnectAuthenticationExchangeResult.cs
deleted file mode 100644
index c60224045..000000000
--- a/MediaBrowser.Model/Connect/ConnectAuthenticationExchangeResult.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-
-namespace MediaBrowser.Model.Connect
-{
- public class ConnectAuthenticationExchangeResult
- {
- /// <summary>
- /// Gets or sets the local user identifier.
- /// </summary>
- /// <value>The local user identifier.</value>
- public string LocalUserId { get; set; }
- /// <summary>
- /// Gets or sets the access token.
- /// </summary>
- /// <value>The access token.</value>
- public string AccessToken { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Connect/ConnectAuthenticationResult.cs b/MediaBrowser.Model/Connect/ConnectAuthenticationResult.cs
deleted file mode 100644
index 0df035e57..000000000
--- a/MediaBrowser.Model/Connect/ConnectAuthenticationResult.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-
-namespace MediaBrowser.Model.Connect
-{
- public class ConnectAuthenticationResult
- {
- /// <summary>
- /// Gets or sets the user.
- /// </summary>
- /// <value>The user.</value>
- public ConnectUser User { get; set; }
- /// <summary>
- /// Gets or sets the access token.
- /// </summary>
- /// <value>The access token.</value>
- public string AccessToken { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Connect/ConnectAuthorization.cs b/MediaBrowser.Model/Connect/ConnectAuthorization.cs
index 84dbf5c36..a949612ab 100644
--- a/MediaBrowser.Model/Connect/ConnectAuthorization.cs
+++ b/MediaBrowser.Model/Connect/ConnectAuthorization.cs
@@ -14,8 +14,8 @@ namespace MediaBrowser.Model.Connect
public ConnectAuthorization()
{
- EnabledLibraries = new string[] {};
- EnabledChannels = new string[] {};
+ EnabledLibraries = Array.Empty<string>();
+ EnabledChannels = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Connect/ConnectAuthorizationRequest.cs b/MediaBrowser.Model/Connect/ConnectAuthorizationRequest.cs
deleted file mode 100644
index ba4e9f5cf..000000000
--- a/MediaBrowser.Model/Connect/ConnectAuthorizationRequest.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.Connect
-{
- public class ConnectAuthorizationRequest
- {
- public string SendingUserId { get; set; }
- public string ConnectUserName { get; set; }
- public string[] EnabledLibraries { get; set; }
- public bool EnableLiveTv { get; set; }
- public string[] EnabledChannels { get; set; }
-
- public ConnectAuthorizationRequest()
- {
- EnabledLibraries = new string[] {};
- EnabledChannels = new string[] {};
- }
- }
-}
diff --git a/MediaBrowser.Model/Devices/DeviceInfo.cs b/MediaBrowser.Model/Devices/DeviceInfo.cs
index 590dc5eb3..a588ce029 100644
--- a/MediaBrowser.Model/Devices/DeviceInfo.cs
+++ b/MediaBrowser.Model/Devices/DeviceInfo.cs
@@ -5,22 +5,6 @@ namespace MediaBrowser.Model.Devices
{
public class DeviceInfo
{
- /// <summary>
- /// Gets or sets the name of the reported.
- /// </summary>
- /// <value>The name of the reported.</value>
- public string ReportedName { get; set; }
- /// <summary>
- /// Gets or sets the name of the custom.
- /// </summary>
- /// <value>The name of the custom.</value>
- public string CustomName { get; set; }
- /// <summary>
- /// Gets or sets the camera upload path.
- /// </summary>
- /// <value>The camera upload path.</value>
- public string CameraUploadPath { get; set; }
-
public string Name { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/Devices/DeviceQuery.cs b/MediaBrowser.Model/Devices/DeviceQuery.cs
index 9ceea1ea8..2838239e4 100644
--- a/MediaBrowser.Model/Devices/DeviceQuery.cs
+++ b/MediaBrowser.Model/Devices/DeviceQuery.cs
@@ -1,14 +1,11 @@

+using System;
+
namespace MediaBrowser.Model.Devices
{
public class DeviceQuery
{
/// <summary>
- /// Gets or sets a value indicating whether [supports unique identifier].
- /// </summary>
- /// <value><c>null</c> if [supports unique identifier] contains no value, <c>true</c> if [supports unique identifier]; otherwise, <c>false</c>.</value>
- public bool? SupportsPersistentIdentifier { get; set; }
- /// <summary>
/// Gets or sets a value indicating whether [supports synchronize].
/// </summary>
/// <value><c>null</c> if [supports synchronize] contains no value, <c>true</c> if [supports synchronize]; otherwise, <c>false</c>.</value>
@@ -17,6 +14,6 @@ namespace MediaBrowser.Model.Devices
/// Gets or sets the user identifier.
/// </summary>
/// <value>The user identifier.</value>
- public string UserId { get; set; }
+ public Guid UserId { get; set; }
}
}
diff --git a/MediaBrowser.Model/Devices/DevicesOptions.cs b/MediaBrowser.Model/Devices/DevicesOptions.cs
index 5bcdd1a82..8e478d005 100644
--- a/MediaBrowser.Model/Devices/DevicesOptions.cs
+++ b/MediaBrowser.Model/Devices/DevicesOptions.cs
@@ -10,15 +10,12 @@ namespace MediaBrowser.Model.Devices
public DevicesOptions()
{
- EnabledCameraUploadDevices = new string[] {};
+ EnabledCameraUploadDevices = Array.Empty<string>();
}
}
public class DeviceOptions
{
- public string[] EnabledCameraUploadDevices { get; set; }
- public string CameraUploadPath { get; set; }
- public bool EnableCameraUploadSubfolders { get; set; }
public string CustomName { get; set; }
}
}
diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs
index 3fb0682b0..ccad4cead 100644
--- a/MediaBrowser.Model/Dlna/ContainerProfile.cs
+++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs
@@ -1,7 +1,5 @@
using System;
-using System.Collections.Generic;
using System.Xml.Serialization;
-using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
@@ -17,7 +15,7 @@ namespace MediaBrowser.Model.Dlna
public ContainerProfile()
{
- Conditions = new ProfileCondition[] { };
+ Conditions = Array.Empty<ProfileCondition>();
}
public string[] GetContainers()
@@ -25,13 +23,11 @@ namespace MediaBrowser.Model.Dlna
return SplitValue(Container);
}
- private static readonly string[] EmptyStringArray = Array.Empty<string>();
-
public static string[] SplitValue(string value)
{
if (string.IsNullOrEmpty(value))
{
- return EmptyStringArray;
+ return Array.Empty<string>();
}
return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
index 966c4a8ce..88d7573e6 100644
--- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
+++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
@@ -1,7 +1,6 @@
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
-using System.Linq;
namespace MediaBrowser.Model.Dlna
{
@@ -28,7 +27,7 @@ namespace MediaBrowser.Model.Dlna
DlnaFlags flagValue = DlnaFlags.BackgroundTransferMode |
DlnaFlags.InteractiveTransferMode |
DlnaFlags.DlnaV15;
-
+
string dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}",
DlnaMaps.FlagsToString(flagValue));
diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
index 4fdf4972f..4cde26a03 100644
--- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
+++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs
@@ -1,13 +1,12 @@
using System;
-using System.Collections.Generic;
using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Model.Dlna
{
public class ResolutionNormalizer
{
- private static readonly ResolutionConfiguration[] Configurations =
- new []
+ private static readonly ResolutionConfiguration[] Configurations =
+ new[]
{
new ResolutionConfiguration(426, 320000),
new ResolutionConfiguration(640, 400000),
@@ -20,24 +19,24 @@ namespace MediaBrowser.Model.Dlna
public static ResolutionOptions Normalize(int? inputBitrate,
int? unused1,
int? unused2,
- int outputBitrate,
- string inputCodec,
+ int outputBitrate,
+ string inputCodec,
string outputCodec,
int? maxWidth,
int? maxHeight)
{
- // If the bitrate isn't changing, then don't downlscale the resolution
- if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
- {
- if (maxWidth.HasValue || maxHeight.HasValue)
- {
- return new ResolutionOptions
- {
- MaxWidth = maxWidth,
- MaxHeight = maxHeight
- };
- }
- }
+ // If the bitrate isn't changing, then don't downlscale the resolution
+ if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
+ {
+ if (maxWidth.HasValue || maxHeight.HasValue)
+ {
+ return new ResolutionOptions
+ {
+ MaxWidth = maxWidth,
+ MaxHeight = maxHeight
+ };
+ }
+ }
var resolutionConfig = GetResolutionConfiguration(outputBitrate);
if (resolutionConfig != null)
@@ -90,8 +89,8 @@ namespace MediaBrowser.Model.Dlna
{
var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
- var scaleFactor = outputScaleFactor/inputScaleFactor;
- var newBitrate = scaleFactor*bitrate;
+ var scaleFactor = outputScaleFactor / inputScaleFactor;
+ var newBitrate = scaleFactor * bitrate;
return Convert.ToInt32(newBitrate);
}
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index 840abf618..41306b4c3 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
using System;
@@ -528,7 +528,7 @@ namespace MediaBrowser.Model.Dlna
{
transcodeReasons.InsertRange(0, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles));
- _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
+ _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
options.Profile.Name ?? "Unknown Profile",
item.Path ?? "Unknown path");
}
@@ -732,7 +732,7 @@ namespace MediaBrowser.Model.Dlna
bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1);
bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1);
- _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
+ _logger.LogInformation("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
options.Profile.Name ?? "Unknown Profile",
item.Path ?? "Unknown path",
isEligibleForDirectPlay,
@@ -1022,7 +1022,7 @@ namespace MediaBrowser.Model.Dlna
if (directPlay == null)
{
- _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
+ _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
profile.Name ?? "Unknown Profile",
mediaSource.Path ?? "Unknown path");
@@ -1188,7 +1188,7 @@ namespace MediaBrowser.Model.Dlna
private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
{
- _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
+ _logger.LogInformation("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
type,
profile.Name ?? "Unknown Profile",
condition.Property,
@@ -1210,7 +1210,7 @@ namespace MediaBrowser.Model.Dlna
if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
{
- _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod);
+ _logger.LogInformation("Not eligible for {0} due to unsupported subtitles", playMethod);
return new ValueTuple<bool, TranscodeReason?>(false, TranscodeReason.SubtitleCodecNotSupported);
}
}
@@ -1397,7 +1397,7 @@ namespace MediaBrowser.Model.Dlna
if (itemBitrate > requestedMaxBitrate)
{
- _logger.Info("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture));
+ _logger.LogInformation("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture));
return false;
}
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index c927cd31c..ba0ac0486 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -18,10 +18,10 @@ namespace MediaBrowser.Model.Dlna
{
public StreamInfo()
{
- AudioCodecs = new string[] { };
- VideoCodecs = new string[] { };
- SubtitleCodecs = new string[] { };
- TranscodeReasons = new TranscodeReason[] { };
+ AudioCodecs = Array.Empty<string>();
+ VideoCodecs = Array.Empty<string>();
+ SubtitleCodecs = Array.Empty<string>();
+ TranscodeReasons = Array.Empty<TranscodeReason>();
StreamOptions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
diff --git a/MediaBrowser.Model/Dlna/SubtitleProfile.cs b/MediaBrowser.Model/Dlna/SubtitleProfile.cs
index a7e61e69a..f85ba4a7a 100644
--- a/MediaBrowser.Model/Dlna/SubtitleProfile.cs
+++ b/MediaBrowser.Model/Dlna/SubtitleProfile.cs
@@ -1,7 +1,5 @@
using MediaBrowser.Model.Extensions;
-using System.Collections.Generic;
using System.Xml.Serialization;
-using MediaBrowser.Model.Dlna;
namespace MediaBrowser.Model.Dlna
{
@@ -43,4 +41,4 @@ namespace MediaBrowser.Model.Dlna
return languages.Length == 0 || ListHelper.ContainsIgnoreCase(languages, subLanguage);
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs
index 3ddbc4150..746d38679 100644
--- a/MediaBrowser.Model/Dto/BaseItemDto.cs
+++ b/MediaBrowser.Model/Dto/BaseItemDto.cs
@@ -4,10 +4,8 @@ using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Sync;
using System;
using System.Collections.Generic;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Model.Dto
{
@@ -67,7 +65,6 @@ namespace MediaBrowser.Model.Dto
public int? AirsBeforeSeasonNumber { get; set; }
public int? AirsAfterSeasonNumber { get; set; }
public int? AirsBeforeEpisodeNumber { get; set; }
- public bool? DisplaySpecialsWithSeasons { get; set; }
public bool? CanDelete { get; set; }
public bool? CanDownload { get; set; }
@@ -156,7 +153,6 @@ namespace MediaBrowser.Model.Dto
/// <value>The channel identifier.</value>
public Guid ChannelId { get; set; }
public string ChannelName { get; set; }
- public string ServiceName { get; set; }
/// <summary>
/// Gets or sets the overview.
@@ -480,26 +476,6 @@ namespace MediaBrowser.Model.Dto
public int? MediaSourceCount { get; set; }
/// <summary>
- /// Determines whether the specified type is type.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <returns><c>true</c> if the specified type is type; otherwise, <c>false</c>.</returns>
- public bool IsType(Type type)
- {
- return IsType(type.Name);
- }
-
- /// <summary>
- /// Determines whether the specified type is type.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <returns><c>true</c> if the specified type is type; otherwise, <c>false</c>.</returns>
- public bool IsType(string type)
- {
- return StringHelper.EqualsIgnoreCase(Type, type);
- }
-
- /// <summary>
/// Gets or sets the image tags.
/// </summary>
/// <value>The image tags.</value>
@@ -602,12 +578,6 @@ namespace MediaBrowser.Model.Dto
public DateTime? EndDate { get; set; }
/// <summary>
- /// Gets or sets the home page URL.
- /// </summary>
- /// <value>The home page URL.</value>
- public string HomePageUrl { get; set; }
-
- /// <summary>
/// Gets or sets the locked fields.
/// </summary>
/// <value>The locked fields.</value>
@@ -678,11 +648,6 @@ namespace MediaBrowser.Model.Dto
public int? IsoSpeedRating { get; set; }
/// <summary>
- /// Used by RecordingGroup
- /// </summary>
- public int? RecordingCount { get; set; }
-
- /// <summary>
/// Gets or sets the series timer identifier.
/// </summary>
/// <value>The series timer identifier.</value>
diff --git a/MediaBrowser.Model/Dto/ChapterInfoDto.cs b/MediaBrowser.Model/Dto/ChapterInfoDto.cs
deleted file mode 100644
index b68b55e70..000000000
--- a/MediaBrowser.Model/Dto/ChapterInfoDto.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using MediaBrowser.Model.Serialization;
-
-namespace MediaBrowser.Model.Dto
-{
- /// <summary>
- /// Class ChapterInfo
- /// </summary>
- public class ChapterInfoDto
- {
- /// <summary>
- /// Gets or sets the start position ticks.
- /// </summary>
- /// <value>The start position ticks.</value>
- public long StartPositionTicks { get; set; }
-
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the image tag.
- /// </summary>
- /// <value>The image tag.</value>
- public string ImageTag { get; set; }
-
- /// <summary>
- /// Gets a value indicating whether this instance has image.
- /// </summary>
- /// <value><c>true</c> if this instance has image; otherwise, <c>false</c>.</value>
- [IgnoreDataMember]
- public bool HasImage
- {
- get { return ImageTag != null; }
- }
- }
-}
diff --git a/MediaBrowser.Model/Dto/GameSystemSummary.cs b/MediaBrowser.Model/Dto/GameSystemSummary.cs
index 252868b66..0f21533a0 100644
--- a/MediaBrowser.Model/Dto/GameSystemSummary.cs
+++ b/MediaBrowser.Model/Dto/GameSystemSummary.cs
@@ -1,5 +1,4 @@
-using System.Collections.Generic;
-using System;
+using System;
namespace MediaBrowser.Model.Dto
{
@@ -43,7 +42,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
public GameSystemSummary()
{
- GameFileExtensions = new string[] {};
+ GameFileExtensions = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
index d1d068fb6..be9c2dff3 100644
--- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
@@ -1,5 +1,4 @@
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
using System.Collections.Generic;
using MediaBrowser.Model.Serialization;
@@ -73,7 +72,7 @@ namespace MediaBrowser.Model.Dto
public MediaSourceInfo()
{
- Formats = new string[] { };
+ Formats = Array.Empty<string>();
MediaStreams = new List<MediaStream>();
RequiredHttpHeaders = new Dictionary<string, string>();
SupportsTranscoding = true;
@@ -115,12 +114,6 @@ namespace MediaBrowser.Model.Dto
public int? DefaultAudioStreamIndex { get; set; }
public int? DefaultSubtitleStreamIndex { get; set; }
- [IgnoreDataMember]
- public MediaStream DefaultAudioStream
- {
- get { return GetDefaultAudioStream(DefaultAudioStreamIndex); }
- }
-
public MediaStream GetDefaultAudioStream(int? defaultIndex)
{
if (defaultIndex.HasValue)
diff --git a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
index aa8b33c81..b7093da71 100644
--- a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
+++ b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Providers;
-using System.Collections.Generic;
+using System;
namespace MediaBrowser.Model.Dto
{
@@ -17,11 +17,11 @@ namespace MediaBrowser.Model.Dto
public MetadataEditorInfo()
{
- ParentalRatingOptions = new ParentalRating[] { };
- Countries = new CountryInfo[] { };
- Cultures = new CultureDto[] { };
- ExternalIdInfos = new ExternalIdInfo[] { };
- ContentTypeOptions = new NameValuePair[] { };
+ ParentalRatingOptions = Array.Empty<ParentalRating>();
+ Countries = Array.Empty<CountryInfo>();
+ Cultures = Array.Empty<CultureDto>();
+ ExternalIdInfos = Array.Empty<ExternalIdInfo>();
+ ContentTypeOptions = Array.Empty<NameValuePair>();
}
}
}
diff --git a/MediaBrowser.Model/Dto/UserDto.cs b/MediaBrowser.Model/Dto/UserDto.cs
index f42c495ad..8d7679fdb 100644
--- a/MediaBrowser.Model/Dto/UserDto.cs
+++ b/MediaBrowser.Model/Dto/UserDto.cs
@@ -2,7 +2,6 @@
using MediaBrowser.Model.Connect;
using MediaBrowser.Model.Users;
using System;
-using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Model.Dto
{
diff --git a/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs b/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
index dfab9add2..2ae7bead2 100644
--- a/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
+++ b/MediaBrowser.Model/Entities/LibraryUpdateInfo.cs
@@ -51,12 +51,12 @@ namespace MediaBrowser.Model.Entities
/// </summary>
public LibraryUpdateInfo()
{
- FoldersAddedTo = new string[] { };
- FoldersRemovedFrom = new string[] { };
- ItemsAdded = new string[] { };
- ItemsRemoved = new string[] { };
- ItemsUpdated = new string[] { };
- CollectionFolders = new string[] { };
+ FoldersAddedTo = Array.Empty<string>();
+ FoldersRemovedFrom = Array.Empty<string>();
+ ItemsAdded = Array.Empty<string>();
+ ItemsRemoved = Array.Empty<string>();
+ ItemsUpdated = Array.Empty<string>();
+ CollectionFolders = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
index 68f713295..c8374f620 100644
--- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
+++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs
@@ -34,7 +34,7 @@ namespace MediaBrowser.Model.Entities
/// </summary>
public VirtualFolderInfo()
{
- Locations = new string[] {};
+ Locations = Array.Empty<string>();
}
/// <summary>
diff --git a/MediaBrowser.Model/Globalization/CultureDto.cs b/MediaBrowser.Model/Globalization/CultureDto.cs
index 6d79aaebb..c0eb8b2ad 100644
--- a/MediaBrowser.Model/Globalization/CultureDto.cs
+++ b/MediaBrowser.Model/Globalization/CultureDto.cs
@@ -46,7 +46,7 @@ namespace MediaBrowser.Model.Globalization
public CultureDto()
{
- ThreeLetterISOLanguageNames = new string[] {};
+ ThreeLetterISOLanguageNames = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Library/UserViewQuery.cs b/MediaBrowser.Model/Library/UserViewQuery.cs
index 8b60cfd98..9801b8e8e 100644
--- a/MediaBrowser.Model/Library/UserViewQuery.cs
+++ b/MediaBrowser.Model/Library/UserViewQuery.cs
@@ -27,7 +27,7 @@ namespace MediaBrowser.Model.Library
public UserViewQuery()
{
IncludeExternalContent = true;
- PresetViews = new string[] {};
+ PresetViews = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
index e3abd5974..5fe77d41e 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
@@ -98,7 +98,7 @@ namespace MediaBrowser.Model.LiveTv
public LiveTvChannelQuery()
{
EnableUserData = true;
- SortBy = new string[] {};
+ SortBy = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvInfo.cs b/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
index 331b1101b..68281d79b 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvInfo.cs
@@ -25,8 +25,8 @@ namespace MediaBrowser.Model.LiveTv
public LiveTvInfo()
{
- Services = new LiveTvServiceInfo[] { };
- EnabledUsers = new string[] {};
+ Services = Array.Empty<LiveTvServiceInfo>();
+ EnabledUsers = Array.Empty<string>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
index eb4f20f9e..6a688c7b4 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
@@ -25,9 +25,9 @@ namespace MediaBrowser.Model.LiveTv
public LiveTvOptions()
{
- TunerHosts = new TunerHostInfo[] { };
- ListingProviders = new ListingsProviderInfo[] { };
- MediaLocationsCreated = new string[] { };
+ TunerHosts = Array.Empty<TunerHostInfo>();
+ ListingProviders = Array.Empty<ListingsProviderInfo>();
+ MediaLocationsCreated = Array.Empty<string>();
RecordingPostProcessorArguments = "\"{path}\"";
}
}
@@ -76,13 +76,13 @@ namespace MediaBrowser.Model.LiveTv
public ListingsProviderInfo()
{
- NewsCategories = new string[] { "news", "journalism", "documentary", "current affairs" };
- SportsCategories = new string[] { "sports", "basketball", "baseball", "football" };
- KidsCategories = new string[] { "kids", "family", "children", "childrens", "disney" };
- MovieCategories = new string[] { "movie" };
- EnabledTuners = new string[] { };
+ NewsCategories = new [] { "news", "journalism", "documentary", "current affairs" };
+ SportsCategories = new [] { "sports", "basketball", "baseball", "football" };
+ KidsCategories = new [] { "kids", "family", "children", "childrens", "disney" };
+ MovieCategories = new [] { "movie" };
+ EnabledTuners = Array.Empty<string>();
EnableAllTuners = true;
- ChannelMappings = new NameValuePair[] {};
+ ChannelMappings = Array.Empty<NameValuePair>();
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
index 23eedfc88..4b7ee971c 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs
@@ -52,7 +52,7 @@ namespace MediaBrowser.Model.LiveTv
public LiveTvServiceInfo()
{
- Tuners = new string[] { };
+ Tuners = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/ProgramQuery.cs b/MediaBrowser.Model/LiveTv/ProgramQuery.cs
deleted file mode 100644
index 89160948c..000000000
--- a/MediaBrowser.Model/LiveTv/ProgramQuery.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using MediaBrowser.Model.Entities;
-using System;
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Model.LiveTv
-{
- /// <summary>
- /// Class ProgramQuery.
- /// </summary>
- public class ProgramQuery
- {
- public ProgramQuery()
- {
- ChannelIds = new Guid[] { };
- OrderBy = new Tuple<string, SortOrder>[] { };
- Genres = new string[] {};
- GenreIds = new Guid[] { };
- EnableTotalRecordCount = true;
- EnableUserData = true;
- }
-
- public bool EnableTotalRecordCount { get; set; }
- public bool EnableUserData { get; set; }
-
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- public bool? EnableImages { get; set; }
- public int? ImageTypeLimit { get; set; }
- public ImageType[] EnableImageTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the channel ids.
- /// </summary>
- /// <value>The channel ids.</value>
- public Guid[] ChannelIds { get; set; }
-
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
- public string SeriesTimerId { get; set; }
- public string Name { get; set; }
-
- /// <summary>
- /// The earliest date for which a program starts to return
- /// </summary>
- public DateTime? MinStartDate { get; set; }
-
- /// <summary>
- /// The latest date for which a program starts to return
- /// </summary>
- public DateTime? MaxStartDate { get; set; }
-
- /// <summary>
- /// The earliest date for which a program ends to return
- /// </summary>
- public DateTime? MinEndDate { get; set; }
-
- /// <summary>
- /// The latest date for which a program ends to return
- /// </summary>
- public DateTime? MaxEndDate { get; set; }
-
- /// <summary>
- /// Used to specific whether to return news or not
- /// </summary>
- /// <remarks>If set to null, all programs will be returned</remarks>
- public bool? IsNews { get; set; }
-
- /// <summary>
- /// Used to specific whether to return movies or not
- /// </summary>
- /// <remarks>If set to null, all programs will be returned</remarks>
- public bool? IsMovie { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is kids.
- /// </summary>
- /// <value><c>null</c> if [is kids] contains no value, <c>true</c> if [is kids]; otherwise, <c>false</c>.</value>
- public bool? IsKids { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is sports.
- /// </summary>
- /// <value><c>null</c> if [is sports] contains no value, <c>true</c> if [is sports]; otherwise, <c>false</c>.</value>
- public bool? IsSports { get; set; }
-
- /// <summary>
- /// Skips over a given number of items within the results. Use for paging.
- /// </summary>
- public int? StartIndex { get; set; }
- public bool? IsSeries { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has aired.
- /// </summary>
- /// <value><c>null</c> if [has aired] contains no value, <c>true</c> if [has aired]; otherwise, <c>false</c>.</value>
- public bool? HasAired { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- public int? Limit { get; set; }
-
- public Tuple<string, SortOrder>[] OrderBy { get; set; }
-
- /// <summary>
- /// Limit results to items containing specific genres
- /// </summary>
- /// <value>The genres.</value>
- public Guid[] GenreIds { get; set; }
- public string[] Genres { get; set; }
- }
-} \ No newline at end of file
diff --git a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs b/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs
deleted file mode 100644
index 9972c4c3f..000000000
--- a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-using System;
-
-namespace MediaBrowser.Model.LiveTv
-{
- public class RecommendedProgramQuery
- {
- /// <summary>
- /// Fields to return within the items, in addition to basic information
- /// </summary>
- /// <value>The fields.</value>
- public ItemFields[] Fields { get; set; }
- public bool? EnableImages { get; set; }
- public int? ImageTypeLimit { get; set; }
- public ImageType[] EnableImageTypes { get; set; }
- public Guid[] GenreIds { get; set; }
-
- public bool EnableTotalRecordCount { get; set; }
-
- public RecommendedProgramQuery()
- {
- EnableTotalRecordCount = true;
- GenreIds = new Guid[] { };
- }
-
- /// <summary>
- /// Gets or sets the user identifier.
- /// </summary>
- /// <value>The user identifier.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is airing.
- /// </summary>
- /// <value><c>true</c> if this instance is airing; otherwise, <c>false</c>.</value>
- public bool? IsAiring { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has aired.
- /// </summary>
- /// <value><c>null</c> if [has aired] contains no value, <c>true</c> if [has aired]; otherwise, <c>false</c>.</value>
- public bool? HasAired { get; set; }
-
- /// <summary>
- /// The maximum number of items to return
- /// </summary>
- /// <value>The limit.</value>
- public int? Limit { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance is movie.
- /// </summary>
- /// <value><c>null</c> if [is movie] contains no value, <c>true</c> if [is movie]; otherwise, <c>false</c>.</value>
- public bool? IsNews { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is movie.
- /// </summary>
- /// <value><c>null</c> if [is movie] contains no value, <c>true</c> if [is movie]; otherwise, <c>false</c>.</value>
- public bool? IsMovie { get; set; }
- public bool? IsSeries { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is kids.
- /// </summary>
- /// <value><c>null</c> if [is kids] contains no value, <c>true</c> if [is kids]; otherwise, <c>false</c>.</value>
- public bool? IsKids { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether this instance is sports.
- /// </summary>
- /// <value><c>null</c> if [is sports] contains no value, <c>true</c> if [is sports]; otherwise, <c>false</c>.</value>
- public bool? IsSports { get; set; }
- }
-} \ No newline at end of file
diff --git a/MediaBrowser.Model/Logging/IConsoleLogger.cs b/MediaBrowser.Model/Logging/IConsoleLogger.cs
deleted file mode 100644
index a8c282d65..000000000
--- a/MediaBrowser.Model/Logging/IConsoleLogger.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace MediaBrowser.Model.Logging
-{
- public interface IConsoleLogger
- {
- void WriteLine(string message);
- }
-}
diff --git a/MediaBrowser.Model/Logging/ILogManager.cs b/MediaBrowser.Model/Logging/ILogManager.cs
deleted file mode 100644
index e6a10cf18..000000000
--- a/MediaBrowser.Model/Logging/ILogManager.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.Logging
-{
- /// <summary>
- /// Interface ILogManager
- /// </summary>
- public interface ILogManager
- {
- /// <summary>
- /// Gets or sets the log level.
- /// </summary>
- /// <value>The log level.</value>
- LogSeverity LogSeverity { get; set; }
-
- /// <summary>
- /// Gets or sets the exception message prefix.
- /// </summary>
- /// <value>The exception message prefix.</value>
- string ExceptionMessagePrefix { get; set; }
-
- /// <summary>
- /// Gets the logger.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <returns>ILogger.</returns>
- ILogger GetLogger(string name);
-
- /// <summary>
- /// Reloads the logger.
- /// </summary>
- Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken);
-
- /// <summary>
- /// Occurs when [logger loaded].
- /// </summary>
- event EventHandler LoggerLoaded;
-
- /// <summary>
- /// Flushes this instance.
- /// </summary>
- void Flush();
-
- /// <summary>
- /// Adds the console output.
- /// </summary>
- void AddConsoleOutput();
-
- /// <summary>
- /// Removes the console output.
- /// </summary>
- void RemoveConsoleOutput();
- }
-}
diff --git a/MediaBrowser.Model/Logging/ILogger.cs b/MediaBrowser.Model/Logging/ILogger.cs
deleted file mode 100644
index be9d6fc50..000000000
--- a/MediaBrowser.Model/Logging/ILogger.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-using System;
-using System.Text;
-
-namespace MediaBrowser.Model.Logging
-{
- /// <summary>
- /// Interface ILogger
- /// </summary>
- public interface ILogger
- {
- /// <summary>
- /// Infoes the specified message.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The param list.</param>
- void Info(string message, params object[] paramList);
-
- /// <summary>
- /// Errors the specified message.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The param list.</param>
- void Error(string message, params object[] paramList);
-
- /// <summary>
- /// Warns the specified message.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The param list.</param>
- void Warn(string message, params object[] paramList);
-
- /// <summary>
- /// Debugs the specified message.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The param list.</param>
- void Debug(string message, params object[] paramList);
-
- /// <summary>
- /// Fatals the specified message.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The param list.</param>
- void Fatal(string message, params object[] paramList);
-
- /// <summary>
- /// Fatals the exception.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="exception">The exception.</param>
- /// <param name="paramList">The param list.</param>
- void FatalException(string message, Exception exception, params object[] paramList);
-
- /// <summary>
- /// Logs the exception.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="exception">The exception.</param>
- /// <param name="paramList">The param list.</param>
- void ErrorException(string message, Exception exception, params object[] paramList);
-
- /// <summary>
- /// Logs the multiline.
- /// </summary>
- /// <param name="message">The message.</param>
- /// <param name="severity">The severity.</param>
- /// <param name="additionalContent">Content of the additional.</param>
- void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent);
-
- /// <summary>
- /// Logs the specified severity.
- /// </summary>
- /// <param name="severity">The severity.</param>
- /// <param name="message">The message.</param>
- /// <param name="paramList">The parameter list.</param>
- void Log(LogSeverity severity, string message, params object[] paramList);
- }
-}
diff --git a/MediaBrowser.Model/Logging/LogHelper.cs b/MediaBrowser.Model/Logging/LogHelper.cs
deleted file mode 100644
index cf1c02186..000000000
--- a/MediaBrowser.Model/Logging/LogHelper.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-using System;
-using System.Text;
-
-namespace MediaBrowser.Model.Logging
-{
- /// <summary>
- /// Class LogHelper
- /// </summary>
- public static class LogHelper
- {
- /// <summary>
- /// Gets the log message.
- /// </summary>
- /// <param name="exception">The exception.</param>
- /// <returns>StringBuilder.</returns>
- public static StringBuilder GetLogMessage(Exception exception)
- {
- if (exception == null)
- {
- throw new ArgumentNullException("exception");
- }
-
- var messageText = new StringBuilder();
-
- messageText.AppendLine(exception.ToString());
-
- messageText.AppendLine(exception.GetType().FullName);
-
- LogExceptionData(messageText, exception);
-
- messageText.AppendLine(exception.StackTrace ?? "No Stack Trace Available");
-
- // Log the InnerExceptions, if any
- AppendInnerExceptions(messageText, exception);
-
- messageText.AppendLine(string.Empty);
-
- return messageText;
- }
-
- /// <summary>
- /// Appends the inner exceptions.
- /// </summary>
- /// <param name="messageText">The message text.</param>
- /// <param name="e">The e.</param>
- private static void AppendInnerExceptions(StringBuilder messageText, Exception e)
- {
- var aggregate = e as AggregateException;
-
- if (aggregate != null && aggregate.InnerExceptions != null)
- {
- foreach (var ex in aggregate.InnerExceptions)
- {
- AppendInnerException(messageText, ex);
- AppendInnerExceptions(messageText, ex);
- }
- }
-
- else if (e.InnerException != null)
- {
- AppendInnerException(messageText, e.InnerException);
- AppendInnerExceptions(messageText, e.InnerException);
- }
- }
-
- /// <summary>
- /// Appends the inner exception.
- /// </summary>
- /// <param name="messageText">The message text.</param>
- /// <param name="e">The e.</param>
- private static void AppendInnerException(StringBuilder messageText, Exception e)
- {
- messageText.AppendLine("InnerException: " + e.GetType().FullName);
- messageText.AppendLine(e.ToString());
-
- LogExceptionData(messageText, e);
-
- if (e.StackTrace != null)
- {
- messageText.AppendLine(e.StackTrace);
- }
- }
-
- /// <summary>
- /// Logs the exception data.
- /// </summary>
- /// <param name="messageText">The message text.</param>
- /// <param name="e">The e.</param>
- private static void LogExceptionData(StringBuilder messageText, Exception e)
- {
- foreach (var key in e.Data.Keys)
- {
- messageText.AppendLine(key + ": " + e.Data[key]);
- }
- }
- }
-}
diff --git a/MediaBrowser.Model/Logging/LogSeverity.cs b/MediaBrowser.Model/Logging/LogSeverity.cs
deleted file mode 100644
index ae0487289..000000000
--- a/MediaBrowser.Model/Logging/LogSeverity.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-
-namespace MediaBrowser.Model.Logging
-{
- /// <summary>
- /// Enum LogSeverity
- /// </summary>
- public enum LogSeverity
- {
- /// <summary>
- /// The info
- /// </summary>
- Info,
- /// <summary>
- /// The debug
- /// </summary>
- Debug,
- /// <summary>
- /// The warn
- /// </summary>
- Warn,
- /// <summary>
- /// The error
- /// </summary>
- Error,
- /// <summary>
- /// The fatal
- /// </summary>
- Fatal
- }
-}
diff --git a/MediaBrowser.Model/Logging/NullLogger.cs b/MediaBrowser.Model/Logging/NullLogger.cs
deleted file mode 100644
index d211d2567..000000000
--- a/MediaBrowser.Model/Logging/NullLogger.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System;
-using System.Text;
-
-namespace MediaBrowser.Model.Logging
-{
- public class NullLogger : ILogger
- {
- public void Info(string message, params object[] paramList)
- {
- }
-
- public void Error(string message, params object[] paramList)
- {
- }
-
- public void Warn(string message, params object[] paramList)
- {
- }
-
- public void Debug(string message, params object[] paramList)
- {
- }
-
- public void Fatal(string message, params object[] paramList)
- {
- }
-
- public void FatalException(string message, Exception exception, params object[] paramList)
- {
- }
-
- public void Log(LogSeverity severity, string message, params object[] paramList)
- {
- }
-
- public void ErrorException(string message, Exception exception, params object[] paramList)
- {
- }
-
- public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent)
- {
- }
- }
-}
diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj
index 1b1a24b68..fe1068842 100644
--- a/MediaBrowser.Model/MediaBrowser.Model.csproj
+++ b/MediaBrowser.Model/MediaBrowser.Model.csproj
@@ -6,7 +6,11 @@
</PropertyGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
</Project>
diff --git a/MediaBrowser.Model/MediaInfo/MediaInfo.cs b/MediaBrowser.Model/MediaInfo/MediaInfo.cs
index 55545e23a..eb8a4434e 100644
--- a/MediaBrowser.Model/MediaInfo/MediaInfo.cs
+++ b/MediaBrowser.Model/MediaInfo/MediaInfo.cs
@@ -7,8 +7,6 @@ namespace MediaBrowser.Model.MediaInfo
{
public class MediaInfo : MediaSourceInfo, IHasProviderIds
{
- private static readonly string[] EmptyStringArray = new string[] {};
-
public ChapterInfo[] Chapters { get; set; }
/// <summary>
@@ -56,13 +54,13 @@ namespace MediaBrowser.Model.MediaInfo
public MediaInfo()
{
- Chapters = new ChapterInfo[] { };
- Artists = new string[] {};
- AlbumArtists = EmptyStringArray;
- Studios = new string[] {};
- Genres = new string[] {};
- People = new BaseItemPerson[] { };
+ Chapters = Array.Empty<ChapterInfo>();
+ Artists = Array.Empty<string>();
+ AlbumArtists = Array.Empty<string>();
+ Studios = Array.Empty<string>();
+ Genres = Array.Empty<string>();
+ People = Array.Empty<BaseItemPerson>();
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
index c68c047f6..91673da9e 100644
--- a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
+++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs
@@ -1,5 +1,4 @@
using MediaBrowser.Model.Dlna;
-using System.Collections.Generic;
using System;
namespace MediaBrowser.Model.MediaInfo
diff --git a/MediaBrowser.Model/News/INewsService.cs b/MediaBrowser.Model/News/INewsService.cs
deleted file mode 100644
index 4c92664d9..000000000
--- a/MediaBrowser.Model/News/INewsService.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using MediaBrowser.Model.Querying;
-
-namespace MediaBrowser.Model.News
-{
- /// <summary>
- /// Interface INewsFeed
- /// </summary>
- public interface INewsService
- {
- /// <summary>
- /// Gets the product news.
- /// </summary>
- /// <param name="query">The query.</param>
- /// <returns>QueryResult{NewsItem}.</returns>
- QueryResult<NewsItem> GetProductNews(NewsQuery query);
- }
-}
diff --git a/MediaBrowser.Model/News/NewsItem.cs b/MediaBrowser.Model/News/NewsItem.cs
deleted file mode 100644
index 2a05c420a..000000000
--- a/MediaBrowser.Model/News/NewsItem.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.News
-{
- public class NewsItem
- {
- public string Title { get; set; }
- public string Link { get; set; }
- public string Description { get; set; }
- public string DescriptionHtml { get; set; }
- public string Guid { get; set; }
- public DateTime Date { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/News/NewsQuery.cs b/MediaBrowser.Model/News/NewsQuery.cs
deleted file mode 100644
index 567888921..000000000
--- a/MediaBrowser.Model/News/NewsQuery.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace MediaBrowser.Model.News
-{
- public class NewsQuery
- {
- public int? StartIndex { get; set; }
-
- public int? Limit { get; set; }
- }
-} \ No newline at end of file
diff --git a/MediaBrowser.Model/Notifications/NotificationOption.cs b/MediaBrowser.Model/Notifications/NotificationOption.cs
index cda9e311d..ce49ae209 100644
--- a/MediaBrowser.Model/Notifications/NotificationOption.cs
+++ b/MediaBrowser.Model/Notifications/NotificationOption.cs
@@ -21,18 +21,6 @@ namespace MediaBrowser.Model.Notifications
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
public bool Enabled { get; set; }
-
- /// <summary>
- /// Gets or sets the title format string.
- /// </summary>
- /// <value>The title format string.</value>
- public string Title { get; set; }
-
- /// <summary>
- /// Gets or sets the description.
- /// </summary>
- /// <value>The description.</value>
- public string Description { get; set; }
/// <summary>
/// Gets or sets the disabled services.
@@ -48,9 +36,9 @@ namespace MediaBrowser.Model.Notifications
public NotificationOption()
{
- DisabledServices = new string[] {};
- DisabledMonitorUsers = new string[] {};
- SendToUsers = new string[] {};
+ DisabledServices = Array.Empty<string>();
+ DisabledMonitorUsers = Array.Empty<string>();
+ SendToUsers = Array.Empty<string>();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Notifications/NotificationRequest.cs b/MediaBrowser.Model/Notifications/NotificationRequest.cs
index 9c89e40fb..7fa57ca9a 100644
--- a/MediaBrowser.Model/Notifications/NotificationRequest.cs
+++ b/MediaBrowser.Model/Notifications/NotificationRequest.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
namespace MediaBrowser.Model.Notifications
{
@@ -22,8 +21,6 @@ namespace MediaBrowser.Model.Notifications
/// </summary>
public string NotificationType { get; set; }
- public Dictionary<string, string> Variables { get; set; }
-
public SendToUserType? SendToUserMode { get; set; }
public NotificationRequest()
diff --git a/MediaBrowser.Model/Notifications/NotificationServiceInfo.cs b/MediaBrowser.Model/Notifications/NotificationServiceInfo.cs
deleted file mode 100644
index 0ffe7d4ae..000000000
--- a/MediaBrowser.Model/Notifications/NotificationServiceInfo.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace MediaBrowser.Model.Notifications
-{
- public class NotificationServiceInfo
- {
- public string Name { get; set; }
- public string Id { get; set; }
- }
-} \ No newline at end of file
diff --git a/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs b/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
index 4c3283d8e..203712fa8 100644
--- a/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
+++ b/MediaBrowser.Model/Notifications/NotificationTypeInfo.cs
@@ -1,5 +1,4 @@
-using System.Collections.Generic;
-using System;
+using System;
namespace MediaBrowser.Model.Notifications
{
@@ -14,16 +13,5 @@ namespace MediaBrowser.Model.Notifications
public string Category { get; set; }
public bool IsBasedOnUserEvent { get; set; }
-
- public string DefaultTitle { get; set; }
-
- public string DefaultDescription { get; set; }
-
- public string[] Variables { get; set; }
-
- public NotificationTypeInfo()
- {
- Variables = new string[] {};
- }
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
index 4c5c8bf51..db2724efa 100644
--- a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
+++ b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs
@@ -1,11 +1,10 @@
-using System.Collections.Generic;
-using System;
+using System;
namespace MediaBrowser.Model.Playlists
{
public class PlaylistCreationRequest
{
- public string Name { get; set; }
+ public string Name { get; set; }
public Guid[] ItemIdList { get; set; }
diff --git a/MediaBrowser.Model/Providers/SubtitleOptions.cs b/MediaBrowser.Model/Providers/SubtitleOptions.cs
index f67b8870d..fde816dd3 100644
--- a/MediaBrowser.Model/Providers/SubtitleOptions.cs
+++ b/MediaBrowser.Model/Providers/SubtitleOptions.cs
@@ -18,10 +18,10 @@ namespace MediaBrowser.Model.Providers
public SubtitleOptions()
{
- DownloadLanguages = new string[] {};
+ DownloadLanguages = Array.Empty<string>();
SkipIfAudioTrackMatches = true;
RequirePerfectMatch = true;
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Querying/QueryFilters.cs b/MediaBrowser.Model/Querying/QueryFilters.cs
index 992bba303..f46650a03 100644
--- a/MediaBrowser.Model/Querying/QueryFilters.cs
+++ b/MediaBrowser.Model/Querying/QueryFilters.cs
@@ -12,10 +12,10 @@ namespace MediaBrowser.Model.Querying
public QueryFiltersLegacy()
{
- Genres = new string[] {};
- Tags = new string[] {};
- OfficialRatings = new string[] {};
- Years = new int[] { };
+ Genres = Array.Empty<string>();
+ Tags = Array.Empty<string>();
+ OfficialRatings = Array.Empty<string>();
+ Years = Array.Empty<int>();
}
}
public class QueryFilters
@@ -25,8 +25,8 @@ namespace MediaBrowser.Model.Querying
public QueryFilters()
{
- Tags = new string[] {};
- Genres = new NameGuidPair[] { };
+ Tags = Array.Empty<string>();
+ Genres = Array.Empty<NameGuidPair>();
}
}
}
diff --git a/MediaBrowser.Model/Search/SearchQuery.cs b/MediaBrowser.Model/Search/SearchQuery.cs
index 6a1861c8e..9ed2f4ffb 100644
--- a/MediaBrowser.Model/Search/SearchQuery.cs
+++ b/MediaBrowser.Model/Search/SearchQuery.cs
@@ -57,9 +57,9 @@ namespace MediaBrowser.Model.Search
IncludePeople = true;
IncludeStudios = true;
- MediaTypes = new string[] {};
- IncludeItemTypes = new string[] {};
- ExcludeItemTypes = new string[] {};
+ MediaTypes = Array.Empty<string>();
+ IncludeItemTypes = Array.Empty<string>();
+ ExcludeItemTypes = Array.Empty<string>();
}
}
}
diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs
index 0a780b910..0ba9988bb 100644
--- a/MediaBrowser.Model/Session/ClientCapabilities.cs
+++ b/MediaBrowser.Model/Session/ClientCapabilities.cs
@@ -12,8 +12,6 @@ namespace MediaBrowser.Model.Session
public bool SupportsMediaControl { get; set; }
public bool SupportsContentUploading { get; set; }
public string MessageCallbackUrl { get; set; }
- public string PushToken { get; set; }
- public string PushTokenType { get; set; }
public bool SupportsPersistentIdentifier { get; set; }
public bool SupportsSync { get; set; }
@@ -25,9 +23,9 @@ namespace MediaBrowser.Model.Session
public ClientCapabilities()
{
- PlayableMediaTypes = new string[] {};
- SupportedCommands = new string[] {};
+ PlayableMediaTypes = Array.Empty<string>();
+ SupportedCommands = Array.Empty<string>();
SupportsPersistentIdentifier = true;
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Session/SessionInfoDto.cs b/MediaBrowser.Model/Session/SessionInfoDto.cs
deleted file mode 100644
index ca14107df..000000000
--- a/MediaBrowser.Model/Session/SessionInfoDto.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using MediaBrowser.Model.Dto;
-using System;
-using System.Collections.Generic;
-
-namespace MediaBrowser.Model.Session
-{
- public class SessionInfoDto
- {
- /// <summary>
- /// Gets or sets the supported commands.
- /// </summary>
- /// <value>The supported commands.</value>
- public string[] SupportedCommands { get; set; }
-
- /// <summary>
- /// Gets or sets the playable media types.
- /// </summary>
- /// <value>The playable media types.</value>
- public string[] PlayableMediaTypes { get; set; }
-
- /// <summary>
- /// Gets or sets the id.
- /// </summary>
- /// <value>The id.</value>
- public string Id { get; set; }
-
- public string ServerId { get; set; }
-
- /// <summary>
- /// Gets or sets the user id.
- /// </summary>
- /// <value>The user id.</value>
- public string UserId { get; set; }
-
- /// <summary>
- /// Gets or sets the user primary image tag.
- /// </summary>
- /// <value>The user primary image tag.</value>
- public string UserPrimaryImageTag { get; set; }
-
- public string RemoteEndPoint { get; set; }
-
- /// <summary>
- /// Gets or sets the name of the user.
- /// </summary>
- /// <value>The name of the user.</value>
- public string UserName { get; set; }
-
- /// <summary>
- /// Gets or sets the additional users present.
- /// </summary>
- /// <value>The additional users present.</value>
- public SessionUserInfo[] AdditionalUsers { get; set; }
-
- /// <summary>
- /// Gets or sets the application version.
- /// </summary>
- /// <value>The application version.</value>
- public string ApplicationVersion { get; set; }
-
- /// <summary>
- /// Gets or sets the type of the client.
- /// </summary>
- /// <value>The type of the client.</value>
- public string Client { get; set; }
-
- /// <summary>
- /// Gets or sets the last activity date.
- /// </summary>
- /// <value>The last activity date.</value>
- public DateTime LastActivityDate { get; set; }
-
- /// <summary>
- /// Gets or sets the name of the device.
- /// </summary>
- /// <value>The name of the device.</value>
- public string DeviceName { get; set; }
-
- public string DeviceType { get; set; }
-
- /// <summary>
- /// Gets or sets the now playing item.
- /// </summary>
- /// <value>The now playing item.</value>
- public BaseItemDto NowPlayingItem { get; set; }
-
- /// <summary>
- /// Gets or sets the device id.
- /// </summary>
- /// <value>The device id.</value>
- public string DeviceId { get; set; }
-
- /// <summary>
- /// Gets or sets the application icon URL.
- /// </summary>
- /// <value>The application icon URL.</value>
- public string AppIconUrl { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [supports remote control].
- /// </summary>
- /// <value><c>true</c> if [supports remote control]; otherwise, <c>false</c>.</value>
- public bool SupportsRemoteControl { get; set; }
-
- public PlayerStateInfo PlayState { get; set; }
-
- public TranscodingInfo TranscodingInfo { get; set; }
-
- public SessionInfoDto()
- {
- AdditionalUsers = new SessionUserInfo[] { };
-
- PlayableMediaTypes = new string[] {};
- SupportedCommands = new string[] {};
- }
- }
-}
diff --git a/MediaBrowser.Model/Sync/SyncJob.cs b/MediaBrowser.Model/Sync/SyncJob.cs
index 0cf9312a1..3b2e30d70 100644
--- a/MediaBrowser.Model/Sync/SyncJob.cs
+++ b/MediaBrowser.Model/Sync/SyncJob.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using MediaBrowser.Model.Sync;
namespace MediaBrowser.Model.Sync
{
@@ -108,7 +106,7 @@ namespace MediaBrowser.Model.Sync
public SyncJob()
{
- RequestedItemIds = new Guid[] { };
+ RequestedItemIds = Array.Empty<Guid>();
}
}
}
diff --git a/MediaBrowser.Model/System/Architecture.cs b/MediaBrowser.Model/System/Architecture.cs
deleted file mode 100644
index 73f78cd58..000000000
--- a/MediaBrowser.Model/System/Architecture.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace MediaBrowser.Model.System
-{
- public enum Architecture
- {
- X86 = 0,
- X64 = 1,
- Arm = 2,
- Arm64 = 3
- }
-}
diff --git a/MediaBrowser.Model/System/IEnvironmentInfo.cs b/MediaBrowser.Model/System/IEnvironmentInfo.cs
index 8cf25a365..6af514dc8 100644
--- a/MediaBrowser.Model/System/IEnvironmentInfo.cs
+++ b/MediaBrowser.Model/System/IEnvironmentInfo.cs
@@ -1,4 +1,5 @@
-
+using System.Runtime.InteropServices;
+
namespace MediaBrowser.Model.System
{
public interface IEnvironmentInfo
diff --git a/MediaBrowser.Model/System/IPowerManagement.cs b/MediaBrowser.Model/System/IPowerManagement.cs
deleted file mode 100644
index 03907568c..000000000
--- a/MediaBrowser.Model/System/IPowerManagement.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-
-namespace MediaBrowser.Model.System
-{
- public interface IPowerManagement
- {
- void PreventSystemStandby();
- void AllowSystemStandby();
- void ScheduleWake(DateTime wakeTimeUtc, string displayName);
- }
-}
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index c790731c6..a63ce5e66 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -1,6 +1,5 @@
using MediaBrowser.Model.Updates;
-using System.Collections.Generic;
-using System;
+using System.Runtime.InteropServices;
namespace MediaBrowser.Model.System
{
@@ -119,12 +118,6 @@ namespace MediaBrowser.Model.System
/// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
public bool HasUpdateAvailable { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether [supports automatic run at startup].
- /// </summary>
- /// <value><c>true</c> if [supports automatic run at startup]; otherwise, <c>false</c>.</value>
- public bool SupportsAutoRunAtStartup { get; set; }
-
public string EncoderLocationType { get; set; }
public Architecture SystemArchitecture { get; set; }
diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
index 7c804348a..9db0041b4 100644
--- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs
+++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
@@ -1,6 +1,6 @@
using System;
using MediaBrowser.Model.Events;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace MediaBrowser.Model.Tasks
{
@@ -29,4 +29,4 @@ namespace MediaBrowser.Model.Tasks
/// </summary>
void Stop();
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs
index 8bddafb5a..e3f6d8620 100644
--- a/MediaBrowser.Model/Users/UserPolicy.cs
+++ b/MediaBrowser.Model/Users/UserPolicy.cs
@@ -78,7 +78,7 @@ namespace MediaBrowser.Model.Users
public UserPolicy()
{
EnableContentDeletion = true;
- EnableContentDeletionFromFolders = new string[] { };
+ EnableContentDeletionFromFolders = Array.Empty<string>();
EnableSyncTranscoding = true;
EnableMediaConversion = true;
@@ -97,20 +97,20 @@ namespace MediaBrowser.Model.Users
EnableSharedDeviceControl = true;
- BlockedTags = new string[] { };
- BlockUnratedItems = new UnratedItem[] { };
+ BlockedTags = Array.Empty<string>();
+ BlockUnratedItems = Array.Empty<UnratedItem>();
EnableUserPreferenceAccess = true;
- AccessSchedules = new AccessSchedule[] { };
+ AccessSchedules = Array.Empty<AccessSchedule>();
EnableAllChannels = true;
- EnabledChannels = new string[] { };
+ EnabledChannels = Array.Empty<string>();
EnableAllFolders = true;
- EnabledFolders = new string[] { };
+ EnabledFolders = Array.Empty<string>();
- EnabledDevices = new string[] { };
+ EnabledDevices = Array.Empty<string>();
EnableAllDevices = true;
EnableContentDownloading = true;
@@ -118,4 +118,4 @@ namespace MediaBrowser.Model.Users
EnableRemoteAccess = true;
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
index 834ec6cd3..707e942f3 100644
--- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs
index 68b96486a..a2143982a 100644
--- a/MediaBrowser.Providers/Books/BookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/BookMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
index 78791906a..7cfae3a12 100644
--- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
+++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Linq;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs
index 634329177..0369e8ca1 100644
--- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs
+++ b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Movies;
diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
index b22db559e..6b371fef9 100644
--- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
+++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Chapters/ChapterManager.cs b/MediaBrowser.Providers/Chapters/ChapterManager.cs
index 3d0c7c964..96e068a1f 100644
--- a/MediaBrowser.Providers/Chapters/ChapterManager.cs
+++ b/MediaBrowser.Providers/Chapters/ChapterManager.cs
@@ -1,20 +1,11 @@
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Chapters;
+using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
namespace MediaBrowser.Providers.Chapters
{
diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
index e472a23c4..bf35cd105 100644
--- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
namespace MediaBrowser.Providers.Folders
diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
index 687dac919..514788261 100644
--- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
index 951794961..14e0c3de6 100644
--- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs
index edde0f5e3..8cc11701e 100644
--- a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs
+++ b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Games/GameMetadataService.cs b/MediaBrowser.Providers/Games/GameMetadataService.cs
index 67becbf58..4a56cc03b 100644
--- a/MediaBrowser.Providers/Games/GameMetadataService.cs
+++ b/MediaBrowser.Providers/Games/GameMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs
index 474dd2fcf..25fdfb713 100644
--- a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs
+++ b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
index 88fba1854..8d764dbb3 100644
--- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs
+++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs
index dfb0c58ad..722de4dee 100644
--- a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs
+++ b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs
index f50dcf1c5..6790f9b33 100644
--- a/MediaBrowser.Providers/Manager/ImageSaver.cs
+++ b/MediaBrowser.Providers/Manager/ImageSaver.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
@@ -164,7 +164,7 @@ namespace MediaBrowser.Providers.Manager
{
var currentPath = currentImagePath;
- _logger.Info("Deleting previous image {0}", currentPath);
+ _logger.LogInformation("Deleting previous image {0}", currentPath);
_libraryMonitor.ReportFileSystemChangeBeginning(currentPath);
@@ -197,7 +197,7 @@ namespace MediaBrowser.Providers.Manager
if (retry)
{
- _logger.Error("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
+ _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
}
else
{
@@ -211,7 +211,7 @@ namespace MediaBrowser.Providers.Manager
if (retry)
{
- _logger.Error("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message);
+ _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath);
}
else
{
@@ -233,7 +233,7 @@ namespace MediaBrowser.Providers.Manager
/// <returns>Task.</returns>
private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
{
- _logger.Debug("Saving image to {0}", path);
+ _logger.LogDebug("Saving image to {0}", path);
var parentFolder = _fileSystem.GetDirectoryName(path);
@@ -271,7 +271,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message);
+ _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
}
}
diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
index c80d43841..fc30374b3 100644
--- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs
+++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using System;
@@ -126,7 +126,7 @@ namespace MediaBrowser.Providers.Manager
if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
{
- _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
+ _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);
@@ -136,7 +136,7 @@ namespace MediaBrowser.Providers.Manager
{
if (response.Protocol == MediaProtocol.Http)
{
- _logger.Debug("Setting image url into item {0}", item.Id);
+ _logger.LogDebug("Setting image url into item {0}", item.Id);
item.SetImage(new ItemImageInfo
{
Path = response.Path,
@@ -173,7 +173,7 @@ namespace MediaBrowser.Providers.Manager
catch (Exception ex)
{
result.ErrorMessage = ex.Message;
- _logger.ErrorException("Error in {0}", ex, provider.Name);
+ _logger.LogError(ex, "Error in {provider}", provider.Name);
}
}
@@ -264,7 +264,7 @@ namespace MediaBrowser.Providers.Manager
return;
}
- _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
+ _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
var images = await _providerManager.GetAvailableRemoteImages(item, new RemoteImageQuery
{
@@ -310,7 +310,7 @@ namespace MediaBrowser.Providers.Manager
catch (Exception ex)
{
result.ErrorMessage = ex.Message;
- _logger.ErrorException("Error in {0}", ex, provider.Name);
+ _logger.LogError(ex, "Error in {provider}", provider.Name);
}
}
@@ -577,7 +577,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (IOException ex)
{
- _logger.ErrorException("Error examining images", ex);
+ _logger.LogError(ex, "Error examining images");
}
}
@@ -586,7 +586,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (HttpException ex)
{
- // Sometimes providers send back bad url's. Just move onto the next image
+ // Sometimes providers send back bad urls. Just move onto the next image
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{
continue;
@@ -596,4 +596,4 @@ namespace MediaBrowser.Providers.Manager
}
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index 57711d3b6..e26004923 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- Logger.ErrorException("Error getting file {0}", ex, path);
+ Logger.LogError(ex, "Error getting file {path}", path);
return null;
}
}
@@ -73,7 +73,7 @@ namespace MediaBrowser.Providers.Manager
if (requiresRefresh)
{
- Logger.Debug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name);
+ Logger.LogDebug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name);
}
}
@@ -96,7 +96,7 @@ namespace MediaBrowser.Providers.Manager
localImagesFailed = true;
if (!(item is IItemByName))
{
- Logger.ErrorException("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name");
+ Logger.LogError(ex, "Error validating images for {0}", item.Path ?? item.Name ?? "Unknown name");
}
}
@@ -268,7 +268,7 @@ namespace MediaBrowser.Providers.Manager
// }
// catch (Exception ex)
// {
- // Logger.ErrorException("Error in AddPersonImage", ex);
+ // Logger.LogError(ex, "Error in AddPersonImage");
// }
//}
@@ -728,7 +728,7 @@ namespace MediaBrowser.Providers.Manager
foreach (var provider in providers.OfType<ILocalMetadataProvider<TItemType>>().ToList())
{
var providerName = provider.GetType().Name;
- Logger.Debug("Running {0} for {1}", providerName, logName);
+ Logger.LogDebug("Running {0} for {1}", providerName, logName);
var itemInfo = new ItemInfo(item);
@@ -759,7 +759,7 @@ namespace MediaBrowser.Providers.Manager
break;
}
- Logger.Debug("{0} returned no metadata for {1}", providerName, logName);
+ Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName);
}
catch (OperationCanceledException)
{
@@ -767,7 +767,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- Logger.ErrorException("Error in {0}", ex, provider.Name);
+ Logger.LogError(ex, "Error in {provider}", provider.Name);
// If a local provider fails, consider that a failure
refreshResult.ErrorMessage = ex.Message;
@@ -826,7 +826,7 @@ namespace MediaBrowser.Providers.Manager
private async Task RunCustomProvider(ICustomMetadataProvider<TItemType> provider, TItemType item, string logName, MetadataRefreshOptions options, RefreshResult refreshResult, CancellationToken cancellationToken)
{
- Logger.Debug("Running {0} for {1}", provider.GetType().Name, logName);
+ Logger.LogDebug("Running {0} for {1}", provider.GetType().Name, logName);
try
{
@@ -839,7 +839,7 @@ namespace MediaBrowser.Providers.Manager
catch (Exception ex)
{
refreshResult.ErrorMessage = ex.Message;
- Logger.ErrorException("Error in {0}", ex, provider.Name);
+ Logger.LogError(ex, "Error in {provider}", provider.Name);
}
}
@@ -857,7 +857,7 @@ namespace MediaBrowser.Providers.Manager
foreach (var provider in providers)
{
var providerName = provider.GetType().Name;
- Logger.Debug("Running {0} for {1}", providerName, logName);
+ Logger.LogDebug("Running {0} for {1}", providerName, logName);
if (id != null && !tmpDataMerged)
{
@@ -880,7 +880,7 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- Logger.Debug("{0} returned no metadata for {1}", providerName, logName);
+ Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName);
}
}
catch (OperationCanceledException)
@@ -891,7 +891,7 @@ namespace MediaBrowser.Providers.Manager
{
refreshResult.Failures++;
refreshResult.ErrorMessage = ex.Message;
- Logger.ErrorException("Error in {0}", ex, provider.Name);
+ Logger.LogError(ex, "Error in {provider}", provider.Name);
}
}
@@ -944,14 +944,14 @@ namespace MediaBrowser.Providers.Manager
//if (hasChanged)
//{
- // Logger.Debug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name);
+ // logger.LogDebug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name);
//}
return hasChanged;
}
catch (Exception ex)
{
- Logger.ErrorException("Error in {0}.HasChanged", ex, changeMonitor.GetType().Name);
+ Logger.LogError(ex, "Error in {0}.HasChanged", changeMonitor.GetType().Name);
return false;
}
}
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index 8697c7c57..8eed5e626 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -1,31 +1,29 @@
-using MediaBrowser.Common.Net;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Providers;
+using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Providers;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Controller.Dto;
using MediaBrowser.Model.Events;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
+using Microsoft.Extensions.Logging;
using Priority_Queue;
-using MediaBrowser.Model.Extensions;
-using MediaBrowser.Controller.Subtitles;
namespace MediaBrowser.Providers.Manager
{
@@ -79,9 +77,9 @@ namespace MediaBrowser.Providers.Manager
/// <summary>
/// Initializes a new instance of the <see cref="ProviderManager" /> class.
/// </summary>
- public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILogManager logManager, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func<ILibraryManager> libraryManagerFactory, IJsonSerializer json)
+ public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILoggerFactory loggerFactory, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func<ILibraryManager> libraryManagerFactory, IJsonSerializer json)
{
- _logger = logManager.GetLogger("ProviderManager");
+ _logger = loggerFactory.CreateLogger("ProviderManager");
_httpClient = httpClient;
ConfigurationManager = configurationManager;
_libraryMonitor = libraryMonitor;
@@ -144,7 +142,7 @@ namespace MediaBrowser.Providers.Manager
return service.RefreshMetadata(item, options, cancellationToken);
}
- _logger.Error("Unable to find a metadata service for item of type " + item.GetType().Name);
+ _logger.LogError("Unable to find a metadata service for item of type {TypeName}", item.GetType().Name);
return Task.FromResult(ItemUpdateType.None);
}
@@ -250,7 +248,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name);
+ _logger.LogError(ex, "{0} failed in GetImageInfos for type {1}", provider.GetType().Name, item.GetType().Name);
return new List<RemoteImageInfo>();
}
}
@@ -329,7 +327,11 @@ namespace MediaBrowser.Providers.Manager
var options = GetMetadataOptions(item);
var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item);
- return GetImageProviders(item, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), includeDisabled).OfType<IRemoteImageProvider>();
+ return GetImageProviders(item, libraryOptions, options,
+ new ImageRefreshOptions(
+ new DirectoryService(_logger, _fileSystem)),
+ includeDisabled)
+ .OfType<IRemoteImageProvider>();
}
private bool CanRefresh(IMetadataProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, bool includeDisabled, bool forceEnableInternetMetadata)
@@ -396,7 +398,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name);
+ _logger.LogError(ex, "{0} failed in Supports for type {1}", provider.GetType().Name, item.GetType().Name);
return false;
}
}
@@ -506,7 +508,11 @@ namespace MediaBrowser.Providers.Manager
var libraryOptions = new LibraryOptions();
- var imageProviders = GetImageProviders(dummy, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), true).ToList();
+ var imageProviders = GetImageProviders(dummy, libraryOptions, options,
+ new ImageRefreshOptions(
+ new DirectoryService(_logger, _fileSystem)),
+ true)
+ .ToList();
var pluginList = summary.Plugins.ToList();
@@ -620,7 +626,7 @@ namespace MediaBrowser.Providers.Manager
foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, updateType, false)))
{
- _logger.Debug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name);
+ _logger.LogDebug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name);
var fileSaver = saver as IMetadataFileSaver;
@@ -634,7 +640,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error in {0} GetSavePath", ex, saver.Name);
+ _logger.LogError(ex, "Error in {0} GetSavePath", saver.Name);
continue;
}
@@ -645,7 +651,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error in metadata saver", ex);
+ _logger.LogError(ex, "Error in metadata saver");
}
finally
{
@@ -660,7 +666,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error in metadata saver", ex);
+ _logger.LogError(ex, "Error in metadata saver");
}
}
}
@@ -723,7 +729,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error in {0}.IsEnabledFor", ex, saver.Name);
+ _logger.LogError(ex, "Error in {0}.IsEnabledFor", saver.Name);
return false;
}
}
@@ -819,13 +825,13 @@ namespace MediaBrowser.Providers.Manager
}
}
}
- catch (Exception ex)
+ catch (Exception)
{
// Logged at lower levels
}
}
- //_logger.Debug("Returning search results {0}", _json.SerializeToString(resultList));
+ //_logger.LogDebug("Returning search results {0}", _json.SerializeToString(resultList));
return resultList;
}
@@ -868,7 +874,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error in {0}.Suports", ex, i.GetType().Name);
+ _logger.LogError(ex, "Error in {0}.Suports", i.GetType().Name);
return false;
}
});
@@ -930,7 +936,7 @@ namespace MediaBrowser.Providers.Manager
public void OnRefreshStart(BaseItem item)
{
- //_logger.Info("OnRefreshStart {0}", item.Id.ToString("N"));
+ //_logger.LogInformation("OnRefreshStart {0}", item.Id.ToString("N"));
var id = item.Id;
lock (_activeRefreshes)
@@ -946,7 +952,7 @@ namespace MediaBrowser.Providers.Manager
public void OnRefreshComplete(BaseItem item)
{
- //_logger.Info("OnRefreshComplete {0}", item.Id.ToString("N"));
+ //_logger.LogInformation("OnRefreshComplete {0}", item.Id.ToString("N"));
lock (_activeRefreshes)
{
_activeRefreshes.Remove(item.Id);
@@ -974,7 +980,7 @@ namespace MediaBrowser.Providers.Manager
public void OnRefreshProgress(BaseItem item, double progress)
{
- //_logger.Info("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress);
+ //_logger.LogInformation("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress);
var id = item.Id;
lock (_activeRefreshes)
@@ -1062,7 +1068,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing item", ex);
+ _logger.LogError(ex, "Error refreshing item");
}
}
@@ -1139,7 +1145,7 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- _logger.ErrorException("Error refreshing library", ex);
+ _logger.LogError(ex, "Error refreshing library");
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
index f7cbf7211..2827a3cc7 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs
@@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.MediaInfo
var file = directoryService.GetFile(path);
if (file != null && file.LastWriteTimeUtc != item.DateModified)
{
- _logger.Debug("Refreshing {0} due to date modified timestamp change.", path);
+ _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path);
return true;
}
}
@@ -84,7 +84,7 @@ namespace MediaBrowser.Providers.MediaInfo
if (!video.SubtitleFiles
.SequenceEqual(_subtitleResolver.GetExternalSubtitleFiles(video, directoryService, false), StringComparer.Ordinal))
{
- _logger.Debug("Refreshing {0} due to external subtitles change.", item.Path);
+ _logger.LogDebug("Refreshing {0} due to external subtitles change.", item.Path);
return true;
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
index c7fc086be..c2fe392ab 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
@@ -14,7 +14,7 @@ using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
@@ -86,7 +86,7 @@ namespace MediaBrowser.Providers.MediaInfo
if (streamFileNames.Length == 0)
{
- _logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
+ _logger.LogError("No playable vobs found in dvd structure, skipping ffprobe.");
return ItemUpdateType.MetadataImport;
}
}
@@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.MediaInfo
if (streamFileNames.Length == 0)
{
- _logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
+ _logger.LogError("No playable vobs found in bluray structure, skipping ffprobe.");
return ItemUpdateType.MetadataImport;
}
}
@@ -342,7 +342,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting BDInfo", ex);
+ _logger.LogError(ex, "Error getting BDInfo");
return null;
}
}
@@ -611,4 +611,4 @@ namespace MediaBrowser.Providers.MediaInfo
.Sum();
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
index 6b396967e..4c66f2b0a 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -176,7 +176,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
catch (Exception ex)
{
- _logger.ErrorException("Error downloading subtitles", ex);
+ _logger.LogError(ex, "Error downloading subtitles");
}
return false;
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
index 6b4181dfb..81abedeb9 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using System;
using System.Collections.Generic;
@@ -148,7 +148,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
catch (Exception ex)
{
- _logger.ErrorException("Error downloading subtitles for {0}", ex, video.Path);
+ _logger.LogError(ex, "Error downloading subtitles for {Path}", video.Path);
}
// Update progress
diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
index 00ffe383f..baf913a77 100644
--- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
@@ -53,7 +53,7 @@ namespace MediaBrowser.Providers.MediaInfo
// Can't extract if we didn't find a video stream in the file
if (!video.DefaultVideoStreamIndex.HasValue)
{
- _logger.Info("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty);
+ _logger.LogInformation("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty);
return Task.FromResult(new DynamicImageResponse { HasImage = false });
}
diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
index 12f78a950..1fce01903 100644
--- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
+++ b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs
index e16e6aa8c..1ebf56e23 100644
--- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs
+++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using System;
@@ -146,7 +146,7 @@ namespace MediaBrowser.Providers.Movies
return _tmdbSettings;
}
- using (var response = await GetMovieDbResponse(new HttpRequestOptions
+ using (HttpResponseInfo response = await GetMovieDbResponse(new HttpRequestOptions
{
Url = string.Format(TmdbConfigUrl, ApiKey),
CancellationToken = cancellationToken,
@@ -154,7 +154,7 @@ namespace MediaBrowser.Providers.Movies
}).ConfigureAwait(false))
{
- using (var json = response.Content)
+ using (Stream json = response.Content)
{
_tmdbSettings = await _jsonSerializer.DeserializeFromStreamAsync<TmdbSettingsResult>(json).ConfigureAwait(false);
@@ -287,7 +287,8 @@ namespace MediaBrowser.Providers.Movies
if (!string.IsNullOrEmpty(language))
{
// They require this to be uppercase
- // https://emby.media/community/index.php?/topic/32454-fr-follow-tmdbs-new-language-api-update/?p=311148
+ // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api.
+ // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
var parts = language.Split('-');
if (parts.Length == 2)
@@ -378,7 +379,7 @@ namespace MediaBrowser.Providers.Movies
!string.IsNullOrEmpty(language) &&
!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
{
- _logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
+ _logger.LogInformation("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
url = string.Format(GetMovieInfo3, id, ApiKey) + "&language=en";
@@ -424,7 +425,7 @@ namespace MediaBrowser.Providers.Movies
if (delayMs > 0)
{
- _logger.Debug("Throttling Tmdb by {0} ms", delayMs);
+ _logger.LogDebug("Throttling Tmdb by {0} ms", delayMs);
await Task.Delay(Convert.ToInt32(delayMs)).ConfigureAwait(false);
}
diff --git a/MediaBrowser.Providers/Movies/MovieDbSearch.cs b/MediaBrowser.Providers/Movies/MovieDbSearch.cs
index 3b4a385d4..b332207e1 100644
--- a/MediaBrowser.Providers/Movies/MovieDbSearch.cs
+++ b/MediaBrowser.Providers/Movies/MovieDbSearch.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using System;
@@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.Movies
year = year ?? yearInName;
}
- _logger.Info("MovieDbProvider: Finding id for item: " + name);
+ _logger.LogInformation("MovieDbProvider: Finding id for item: " + name);
var language = idInfo.MetadataLanguage.ToLower();
//nope - search for it
diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
index f0674ac9b..958153334 100644
--- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs
+++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
index 338fc1c6d..ae81545a6 100644
--- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Music/ArtistMetadataService.cs b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
index 7741a3f43..7dc4a8dfe 100644
--- a/MediaBrowser.Providers/Music/ArtistMetadataService.cs
+++ b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs
index f02eae19f..6952ee856 100644
--- a/MediaBrowser.Providers/Music/AudioMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs
index d16376426..2c94d6a07 100644
--- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs
+++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using System;
using System.Collections.Generic;
@@ -720,82 +720,6 @@ namespace MediaBrowser.Providers.Music
return null;
}
- private long _lastMbzUrlQueryTicks = 0;
- private List<MbzUrl> _mbzUrls = null;
- private MbzUrl _chosenUrl;
-
- private async Task<MbzUrl> GetMbzUrl(bool forceMusicBrainzProper = false)
- {
- if (_chosenUrl == null || _mbzUrls == null || (DateTime.UtcNow.Ticks - _lastMbzUrlQueryTicks) > TimeSpan.FromHours(12).Ticks)
- {
- var urls = await RefreshMzbUrls(forceMusicBrainzProper).ConfigureAwait(false);
-
- if (urls.Count > 1)
- {
- _chosenUrl = urls[new Random().Next(0, urls.Count)];
- }
- else
- {
- _chosenUrl = urls[0];
- }
- }
-
- return _chosenUrl;
- }
-
- private async Task<List<MbzUrl>> RefreshMzbUrls(bool forceMusicBrainzProper = false)
- {
- List<MbzUrl> list = null;
-
- if (!forceMusicBrainzProper)
- {
- var musicbrainzadminurl = _appHost.GetValue("musicbrainzadminurl");
-
- if (!string.IsNullOrEmpty(musicbrainzadminurl))
- {
- try
- {
- var options = new HttpRequestOptions
- {
- Url = musicbrainzadminurl,
- UserAgent = _appHost.Name + "/" + _appHost.ApplicationVersion
- };
-
- using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
- {
- using (var stream = response.Content)
- {
- var results = await _json.DeserializeFromStreamAsync<List<MbzUrl>>(stream).ConfigureAwait(false);
-
- list = results;
- }
- }
- _lastMbzUrlQueryTicks = DateTime.UtcNow.Ticks;
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error getting music brainz info", ex);
- }
- }
- }
-
- if (list == null)
- {
- list = new List<MbzUrl>
- {
- new MbzUrl
- {
- url = MusicBrainzBaseUrl,
- throttleMs = 1000
- }
- };
- }
-
- _mbzUrls = list.ToList();
-
- return list;
- }
-
internal Task<HttpResponseInfo> GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken)
{
return GetMusicBrainzResponse(url, isSearch, false, cancellationToken);
@@ -806,13 +730,13 @@ namespace MediaBrowser.Providers.Music
/// </summary>
internal async Task<HttpResponseInfo> GetMusicBrainzResponse(string url, bool isSearch, bool forceMusicBrainzProper, CancellationToken cancellationToken)
{
- var urlInfo = await GetMbzUrl(forceMusicBrainzProper).ConfigureAwait(false);
+ var urlInfo = new MbzUrl(MusicBrainzBaseUrl, 1000);
var throttleMs = urlInfo.throttleMs;
if (throttleMs > 0)
{
// MusicBrainz is extremely adamant about limiting to one request per second
- _logger.Debug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture));
+ _logger.LogDebug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture));
await Task.Delay(throttleMs, cancellationToken).ConfigureAwait(false);
}
@@ -841,6 +765,12 @@ namespace MediaBrowser.Providers.Music
internal class MbzUrl
{
+ internal MbzUrl(string url, int throttleMs)
+ {
+ this.url = url;
+ this.throttleMs = throttleMs;
+ }
+
public string url { get; set; }
public int throttleMs { get; set; }
}
diff --git a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
index 28504dbd7..54d68bfd5 100644
--- a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
+++ b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
index 3828f8d27..6c9bc526d 100644
--- a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
+++ b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
index 8c7ef71b6..39d9b39ee 100644
--- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
+++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using System;
diff --git a/MediaBrowser.Providers/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Omdb/OmdbProvider.cs
index 5c4eb62a8..bb4624b5c 100644
--- a/MediaBrowser.Providers/Omdb/OmdbProvider.cs
+++ b/MediaBrowser.Providers/Omdb/OmdbProvider.cs
@@ -270,21 +270,13 @@ namespace MediaBrowser.Providers.Omdb
public static string GetOmdbUrl(string query, IApplicationHost appHost, CancellationToken cancellationToken)
{
- var baseUrl = appHost.GetValue("omdb_baseurl");
+ const string url = "https://www.omdbapi.com?apikey=fe53f97e";
- if (string.IsNullOrEmpty(baseUrl))
+ if (string.IsNullOrWhiteSpace(query))
{
- baseUrl = "https://www.omdbapi.com";
+ return url;
}
-
- var url = baseUrl + "?apikey=fe53f97e";
-
- if (!string.IsNullOrWhiteSpace(query))
- {
- url += "&" + query;
- }
-
- return url;
+ return url + "&" + query;
}
private async Task<string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs
index 7af058bcd..dda1fc511 100644
--- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs
+++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
namespace MediaBrowser.Providers.People
diff --git a/MediaBrowser.Providers/People/PersonMetadataService.cs b/MediaBrowser.Providers/People/PersonMetadataService.cs
index bbfaa43b4..e32ecaa64 100644
--- a/MediaBrowser.Providers/People/PersonMetadataService.cs
+++ b/MediaBrowser.Providers/People/PersonMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
index bff933ccf..f6d3724e9 100644
--- a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
index d7f4982e4..87529f93a 100644
--- a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
index da4873ca4..7bc2469a0 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
@@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
@@ -169,7 +169,7 @@ namespace MediaBrowser.Providers.Playlists
var file = directoryService.GetFile(path);
if (file != null && file.LastWriteTimeUtc != item.DateModified)
{
- _logger.Debug("Refreshing {0} due to date modified timestamp change.", path);
+ _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path);
return true;
}
}
diff --git a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
index 1d6591792..9534a4759 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using System.Linq;
diff --git a/MediaBrowser.Providers/Studios/StudioMetadataService.cs b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
index 23953b0d3..0c07fb541 100644
--- a/MediaBrowser.Providers/Studios/StudioMetadataService.cs
+++ b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
index 071687c0f..f9348a761 100644
--- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
+++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
@@ -1,5 +1,4 @@
-using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
@@ -8,7 +7,7 @@ using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using System;
using System.Collections.Generic;
@@ -101,7 +100,7 @@ namespace MediaBrowser.Providers.Subtitles
}
catch (Exception ex)
{
- _logger.ErrorException("Error downloading subtitles from {0}", ex, provider.Name);
+ _logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name);
}
}
return new RemoteSubtitleInfo[] { };
@@ -119,7 +118,7 @@ namespace MediaBrowser.Providers.Subtitles
}
catch (Exception ex)
{
- _logger.ErrorException("Error downloading subtitles from {0}", ex, i.Name);
+ _logger.LogError(ex, "Error downloading subtitles from {0}", i.Name);
return new RemoteSubtitleInfo[] { };
}
});
@@ -189,13 +188,12 @@ namespace MediaBrowser.Providers.Subtitles
}
catch (Exception ex)
{
- EventHelper.FireEventIfNotNull(SubtitleDownloadFailure, this, new SubtitleDownloadFailureEventArgs
+ SubtitleDownloadFailure?.Invoke(this, new SubtitleDownloadFailureEventArgs
{
Item = video,
Exception = ex,
Provider = provider.Name
-
- }, _logger);
+ });
throw;
}
@@ -207,7 +205,7 @@ namespace MediaBrowser.Providers.Subtitles
foreach (var savePath in savePaths)
{
- _logger.Info("Saving subtitles to {0}", savePath);
+ _logger.LogInformation("Saving subtitles to {0}", savePath);
_monitor.ReportFileSystemChangeBeginning(savePath);
diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs
index 4f528086e..797005c41 100644
--- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs
+++ b/MediaBrowser.Providers/TV/DummySeasonProvider.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Globalization;
using System.Linq;
using System.Threading;
@@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV
_libraryManager.GetLibraryOptions(series).SeasonZeroDisplayName :
(seasonNumber.HasValue ? string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value.ToString(_usCulture)) : _localization.GetLocalizedString("NameSeasonUnknown"));
- _logger.Info("Creating Season {0} entry for {1}", seasonName, series.Name);
+ _logger.LogInformation("Creating Season {0} entry for {1}", seasonName, series.Name);
var season = new Season
{
@@ -147,7 +147,7 @@ namespace MediaBrowser.Providers.TV
series.AddChild(season, cancellationToken);
- await season.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
+ await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
return season;
}
@@ -192,7 +192,7 @@ namespace MediaBrowser.Providers.TV
foreach (var seasonToRemove in seasonsToRemove)
{
- _logger.Info("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber);
+ _logger.LogInformation("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber);
_libraryManager.DeleteItem(seasonToRemove, new DeleteOptions
{
diff --git a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
index cea907ca3..6292d9cf2 100644
--- a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
+++ b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using System.Threading.Tasks;
diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
index 6e469a041..19f3c07d2 100644
--- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -217,7 +217,7 @@ namespace MediaBrowser.Providers.TV
if (addMissingEpisodes)
{
// tvdb has a lot of nearly blank episodes
- _logger.Info("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2);
+ _logger.LogInformation("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2);
await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false);
hasChanges = true;
@@ -226,7 +226,7 @@ namespace MediaBrowser.Providers.TV
else if (airDate.Value > now)
{
// tvdb has a lot of nearly blank episodes
- _logger.Info("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2);
+ _logger.LogInformation("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2);
await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false);
hasChanges = true;
@@ -414,7 +414,7 @@ namespace MediaBrowser.Providers.TV
season.AddChild(episode, cancellationToken);
- await episode.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
+ await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
}
/// <summary>
diff --git a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
index e65c36d98..c62f58eb4 100644
--- a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Omdb;
diff --git a/MediaBrowser.Providers/TV/SeasonMetadataService.cs b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
index a9a026db9..aad0e26a0 100644
--- a/MediaBrowser.Providers/TV/SeasonMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index 338e7b4ed..1cb06efdf 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System;
using System.Collections.Generic;
@@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.TV
}
catch (Exception ex)
{
- Logger.ErrorException("Error in DummySeasonProvider", ex);
+ Logger.LogError(ex, "Error in DummySeasonProvider");
}
}
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs
index f6568510d..d9933ba2a 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Movies;
@@ -25,8 +25,8 @@ namespace MediaBrowser.Providers.TV
IRemoteImageProvider,
IHasOrder
{
- public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager)
- : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager)
+ public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
+ : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
{}
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
index 31785ca9c..095ce0e17 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
@@ -27,8 +27,8 @@ namespace MediaBrowser.Providers.TV
IRemoteMetadataProvider<Episode, EpisodeInfo>,
IHasOrder
{
- public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager)
- : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager)
+ public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
+ : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
{ }
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs
index 4d7cec79f..facf5cadf 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Model.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Movies;
using System;
@@ -26,14 +26,14 @@ namespace MediaBrowser.Providers.TV
private readonly ILocalizationManager _localization;
private readonly ILogger _logger;
- public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager)
+ public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
{
_httpClient = httpClient;
_configurationManager = configurationManager;
_jsonSerializer = jsonSerializer;
_fileSystem = fileSystem;
_localization = localization;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
}
protected ILogger Logger
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs
index 63484483f..217dab663 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
@@ -32,14 +32,14 @@ namespace MediaBrowser.Providers.TV
private readonly ILocalizationManager _localization;
private readonly ILogger _logger;
- public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILogManager logManager)
+ public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory)
{
_httpClient = httpClient;
_configurationManager = configurationManager;
_fileSystem = fileSystem;
_localization = localization;
_jsonSerializer = jsonSerializer;
- _logger = logManager.GetLogger(GetType().Name);
+ _logger = loggerFactory.CreateLogger(GetType().Name);
}
public async Task<MetadataResult<Season>> GetMetadata(SeasonInfo info, CancellationToken cancellationToken)
@@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.TV
}
catch (HttpException ex)
{
- _logger.Error("No metadata found for {0}", seasonNumber.Value);
+ _logger.LogError(ex, "No metadata found for {0}", seasonNumber.Value);
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
index 7f9465f1c..c3981ae8f 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
@@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Movies;
@@ -412,7 +412,7 @@ namespace MediaBrowser.Providers.TV
!string.IsNullOrEmpty(language) &&
!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
{
- _logger.Info("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English...");
+ _logger.LogInformation("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English...");
url = string.Format(GetTvInfo3, id, MovieDbProvider.ApiKey) + "&language=en";
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
index 41155aca1..d1d8e32c2 100644
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Providers;
using System;
using System.Collections.Generic;
@@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV
}
else
{
- _logger.Debug("No series identity found for {0}", searchInfo.Name);
+ _logger.LogDebug("No series identity found for {0}", searchInfo.Name);
}
return result;
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs
index 2839cb434..8bab59595 100644
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs
+++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
@@ -358,7 +358,7 @@ namespace MediaBrowser.Providers.TV
}
catch (HttpException ex)
{
- _logger.ErrorException("Error updating tvdb series id {0}, language {1}", ex, seriesId, language);
+ _logger.LogError(ex, "Error updating tvdb series id {ID}, language {Language}", seriesId, language);
// Already logged at lower levels, but don't fail the whole operation, unless timed out
// We have to fail this to make it run again otherwise new episode data could potentially be missing
@@ -389,7 +389,7 @@ namespace MediaBrowser.Providers.TV
/// <returns>Task.</returns>
private Task UpdateSeries(string id, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken)
{
- _logger.Info("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage);
+ _logger.LogInformation("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage);
seriesDataPath = Path.Combine(seriesDataPath, id);
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
index 8b7efc28b..515f58c27 100644
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
+++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using System;
diff --git a/MediaBrowser.Providers/Users/UserMetadataService.cs b/MediaBrowser.Providers/Users/UserMetadataService.cs
index 694315c18..361d42f50 100644
--- a/MediaBrowser.Providers/Users/UserMetadataService.cs
+++ b/MediaBrowser.Providers/Users/UserMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Providers/Videos/VideoMetadataService.cs b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
index f493eb31f..b9868cea9 100644
--- a/MediaBrowser.Providers/Videos/VideoMetadataService.cs
+++ b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.Providers/Years/YearMetadataService.cs b/MediaBrowser.Providers/Years/YearMetadataService.cs
index 783833656..d62cb10b5 100644
--- a/MediaBrowser.Providers/Years/YearMetadataService.cs
+++ b/MediaBrowser.Providers/Years/YearMetadataService.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj
deleted file mode 100644
index 480b422bc..000000000
--- a/MediaBrowser.Server.Mono/EmbyServer.csproj
+++ /dev/null
@@ -1,55 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <OutputType>Exe</OutputType>
- <AssemblyName>jellyfin</AssemblyName>
- <TargetFramework>netcoreapp2.1</TargetFramework>
- <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
- </PropertyGroup>
-
- <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
- <DebugType>None</DebugType>
- <RuntimeIdentifiers>ubuntu.16.04-x64</RuntimeIdentifiers>
- </PropertyGroup>
-
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <PlatformTarget>AnyCPU</PlatformTarget>
- </PropertyGroup>
-
- <ItemGroup>
- <PackageReference Include="Mono.Posix.NETStandard" Version="1.0.0" />
- <PackageReference Include="SkiaSharp" Version="1.68.0" />
- <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="1.1.11" />
- <PackageReference Include="SQLitePCLRaw.core" Version="1.1.11" />
- <PackageReference Include="SQLitePCLRaw.provider.sqlite3.netstandard11" Version="1.1.11" />
- </ItemGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\Emby.IsoMounting\IsoMounter\IsoMounter.csproj" />
- <ProjectReference Include="..\BDInfo\BDInfo.csproj" />
- <ProjectReference Include="..\DvdLib\DvdLib.csproj" />
- <ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
- <ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
- <ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
- <ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
- <ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
- <ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
- <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
- <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
- <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
- <ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
- <ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
- <ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
- <ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
- <ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
- <ProjectReference Include="..\RSSDP\RSSDP.csproj" />
- <ProjectReference Include="..\Emby.Drawing.Skia\Emby.Drawing.Skia.csproj" />
- <ProjectReference Include="..\Emby.Drawing.ImageMagick\Emby.Drawing.ImageMagick.csproj" />
- <ProjectReference Include="..\SocketHttpListener\SocketHttpListener.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <Compile Include="..\SharedVersion.cs" />
- </ItemGroup>
-
-</Project>
diff --git a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs
deleted file mode 100644
index 49955ad65..000000000
--- a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using System;
-using Emby.Drawing;
-using Emby.Drawing.ImageMagick;
-using Emby.Server.Implementations;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
-using Emby.Drawing.Skia;
-using MediaBrowser.Model.System;
-using MediaBrowser.Model.Globalization;
-
-namespace MediaBrowser.Server.Startup.Common
-{
- public class ImageEncoderHelper
- {
- public static IImageEncoder GetImageEncoder(ILogger logger,
- ILogManager logManager,
- IFileSystem fileSystem,
- StartupOptions startupOptions,
- Func<IHttpClient> httpClient,
- IApplicationPaths appPaths,
- IEnvironmentInfo environment,
- ILocalizationManager localizationManager)
- {
- if (!startupOptions.ContainsOption("-enablegdi"))
- {
- try
- {
- return new SkiaEncoder(logManager.GetLogger("Skia"), appPaths, httpClient, fileSystem, localizationManager);
- }
- catch (Exception ex)
- {
- logger.Info("Skia not available. Will try next image processor. {0}", ex.Message);
- }
-
- try
- {
- return new ImageMagickEncoder(logManager.GetLogger("ImageMagick"), appPaths, httpClient, fileSystem, environment);
- }
- catch
- {
- logger.Info("ImageMagick not available. Will try next image processor.");
- }
- }
-
- return new NullImageEncoder();
- }
- }
-}
diff --git a/MediaBrowser.Server.Mono/MonoAppHost.cs b/MediaBrowser.Server.Mono/MonoAppHost.cs
deleted file mode 100644
index 576eb5c68..000000000
--- a/MediaBrowser.Server.Mono/MonoAppHost.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-//using Emby.Server.CinemaMode;
-using Emby.Server.Implementations;
-using Emby.Server.Implementations.Library;
-using Emby.Server.Implementations.HttpServer;
-using Emby.Server.Implementations.Net;
-using MediaBrowser.Controller.Connect;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Sync;
-using IsoMounter;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.Services;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Server.Mono
-{
- public class MonoAppHost : ApplicationHost
- {
- public MonoAppHost(ServerApplicationPaths applicationPaths, ILogManager logManager, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) : base(applicationPaths, logManager, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager)
- {
- }
-
- public override bool CanSelfRestart
- {
- get
- {
- // A restart script must be provided
- return StartupOptions.ContainsOption("-restartpath");
- }
- }
-
- //protected override ISyncManager CreateSyncManager()
- //{
- // return new SyncManager();
- //}
-
- protected override void RestartInternal()
- {
- MainClass.Restart();
- }
-
- protected override List<Assembly> GetAssembliesWithPartsInternal()
- {
- var list = new List<Assembly>();
-
- list.Add(GetType().Assembly);
-
- return list;
- }
-
- protected override void ShutdownInternal()
- {
- MainClass.Shutdown();
- }
-
- protected override bool SupportsDualModeSockets
- {
- get
- {
- return GetMonoVersion() >= new Version(4, 6);
- }
- }
-
- private static Version GetMonoVersion()
- {
- Type type = Type.GetType("Mono.Runtime");
- if (type != null)
- {
- MethodInfo displayName = type.GetTypeInfo().GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
- var displayNameValue = displayName.Invoke(null, null).ToString().Trim().Split(' ')[0];
-
- Version version;
- if (Version.TryParse(displayNameValue, out version))
- {
- return version;
- }
- }
-
- return new Version(1, 0);
- }
-
- protected override IHttpListener CreateHttpListener()
- {
- return new EmbyServer.SocketSharp.WebSocketSharpListener(LogManager.GetLogger("HttpServer"),
- Certificate,
- StreamHelper,
- TextEncoding,
- NetworkManager,
- SocketFactory,
- CryptographyProvider,
- SupportsDualModeSockets,
- FileSystemManager,
- EnvironmentInfo);
- }
-
- }
-}
diff --git a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs
deleted file mode 100644
index 2fd95ab82..000000000
--- a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using Emby.Server.Implementations.IO;
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Model.System;
-using Mono.Unix.Native;
-
-namespace MediaBrowser.Server.Mono.Native
-{
- public class MonoFileSystem : ManagedFileSystem
- {
- public MonoFileSystem(ILogger logger, IEnvironmentInfo environment, string defaultDirectory, string tempPath, bool enableSeperateFileAndDirectoryQueries)
- : base(logger, environment,defaultDirectory, tempPath, enableSeperateFileAndDirectoryQueries)
- {
- }
-
- public override void SetExecutable(string path)
- {
- // Linux: File permission to 666, and user's execute bit
- Logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path);
-
- Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH);
- }
- }
-}
diff --git a/MediaBrowser.Server.Mono/Native/PowerManagement.cs b/MediaBrowser.Server.Mono/Native/PowerManagement.cs
deleted file mode 100644
index 219a69d65..000000000
--- a/MediaBrowser.Server.Mono/Native/PowerManagement.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using MediaBrowser.Model.System;
-
-namespace MediaBrowser.Server.Mono.Native
-{
- public class PowerManagement : IPowerManagement
- {
- public void PreventSystemStandby()
- {
- }
-
- public void AllowSystemStandby()
- {
- }
-
- public void ScheduleWake(DateTime wakeTimeUtc, string displayName)
- {
- // nothing to Do
- }
- }
-}
diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs
deleted file mode 100644
index 887a9545f..000000000
--- a/MediaBrowser.Server.Mono/Program.cs
+++ /dev/null
@@ -1,326 +0,0 @@
-using MediaBrowser.Model.Logging;
-using MediaBrowser.Server.Mono.Native;
-using MediaBrowser.Server.Startup.Common;
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Security;
-using System.Reflection;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-using Emby.Drawing;
-using Emby.Server.Implementations;
-using Emby.Server.Implementations.EnvironmentInfo;
-using Emby.Server.Implementations.IO;
-using Emby.Server.Implementations.Logging;
-using Emby.Server.Implementations.Networking;
-using MediaBrowser.Controller;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Mono.Unix.Native;
-using ILogger = MediaBrowser.Model.Logging.ILogger;
-using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
-using System.Threading;
-using InteropServices = System.Runtime.InteropServices;
-
-namespace MediaBrowser.Server.Mono
-{
- public class MainClass
- {
- private static ILogger _logger;
- private static IFileSystem FileSystem;
- private static IServerApplicationPaths _appPaths;
- private static ILogManager _logManager;
-
- private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
- private static bool _restartOnShutdown;
-
- public static void Main(string[] args)
- {
- var applicationPath = Assembly.GetEntryAssembly().Location;
-
- SetSqliteProvider();
-
- var options = new StartupOptions(Environment.GetCommandLineArgs());
-
- // Allow this to be specified on the command line.
- var customProgramDataPath = options.GetOption("-programdata");
-
- var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
- _appPaths = appPaths;
-
- using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
- {
- _logManager = logManager;
-
- var task = logManager.ReloadLogger(LogSeverity.Debug, CancellationToken.None);
- Task.WaitAll(task);
- logManager.AddConsoleOutput();
-
- var logger = _logger = logManager.GetLogger("Main");
-
- ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
-
- AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
-
- RunApplication(appPaths, logManager, options);
-
- _logger.Info("Disposing app host");
-
- if (_restartOnShutdown)
- {
- StartNewInstance(options);
- }
- }
- }
-
- private static void SetSqliteProvider()
- {
- // SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
- //SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
- SQLitePCL.Batteries_V2.Init();
- }
-
- private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
- {
- if (string.IsNullOrEmpty(programDataPath))
- {
- if (InteropServices.RuntimeInformation.IsOSPlatform(InteropServices.OSPlatform.Windows))
- {
- programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
- }
- else
- {
- // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
- programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
- // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
- if (string.IsNullOrEmpty(programDataPath)){
- programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
- }
- }
- programDataPath = Path.Combine(programDataPath, "jellyfin");
- }
-
- var appFolderPath = Path.GetDirectoryName(applicationPath);
-
- return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
- }
-
- private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
- {
- // Allow all https requests
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
-
- var environmentInfo = GetEnvironmentInfo();
-
- var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
-
- FileSystem = fileSystem;
-
- using (var appHost = new MonoAppHost(appPaths,
- logManager,
- options,
- fileSystem,
- new PowerManagement(),
- "embyserver-mono_{version}.zip",
- environmentInfo,
- new NullImageEncoder(),
- new SystemEvents(logManager.GetLogger("SystemEvents")),
- new NetworkManager(logManager.GetLogger("NetworkManager"), environmentInfo)))
- {
- if (options.ContainsOption("-v"))
- {
- Console.WriteLine(appHost.ApplicationVersion.ToString());
- return;
- }
-
- Console.WriteLine("appHost.Init");
-
- appHost.Init();
-
- appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
-
- Console.WriteLine("Running startup tasks");
-
- var task = appHost.RunStartupTasks();
- Task.WaitAll(task);
-
- task = ApplicationTaskCompletionSource.Task;
-
- Task.WaitAll(task);
- }
- }
-
- private static MonoEnvironmentInfo GetEnvironmentInfo()
- {
- var info = new MonoEnvironmentInfo();
-
- var uname = GetUnixName();
-
- var sysName = uname.sysname ?? string.Empty;
-
- if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
- {
- info.OperatingSystem = Model.System.OperatingSystem.OSX;
- }
- else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
- {
- info.OperatingSystem = Model.System.OperatingSystem.Linux;
- }
- else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
- {
- info.OperatingSystem = Model.System.OperatingSystem.BSD;
- }
-
- var archX86 = new Regex("(i|I)[3-6]86");
-
- if (archX86.IsMatch(uname.machine))
- {
- info.SystemArchitecture = Architecture.X86;
- }
- else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
- {
- info.SystemArchitecture = Architecture.X64;
- }
- else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
- {
- info.SystemArchitecture = Architecture.Arm;
- }
- else if (System.Environment.Is64BitOperatingSystem)
- {
- info.SystemArchitecture = Architecture.X64;
- }
- else
- {
- info.SystemArchitecture = Architecture.X86;
- }
-
- return info;
- }
-
- private static Uname _unixName;
-
- private static Uname GetUnixName()
- {
- if (_unixName == null)
- {
- var uname = new Uname();
- try
- {
- Utsname utsname;
- var callResult = Syscall.uname(out utsname);
- if (callResult == 0)
- {
- uname.sysname = utsname.sysname ?? string.Empty;
- uname.machine = utsname.machine ?? string.Empty;
- }
-
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error getting unix name", ex);
- }
- _unixName = uname;
- }
- return _unixName;
- }
-
- public class Uname
- {
- public string sysname = string.Empty;
- public string machine = string.Empty;
- }
-
- /// <summary>
- /// Handles the UnhandledException event of the CurrentDomain control.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
- static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
- {
- var exception = (Exception)e.ExceptionObject;
-
- new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
-
- if (!Debugger.IsAttached)
- {
- var message = LogHelper.GetLogMessage(exception).ToString();
-
- if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 &&
- message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1)
- {
- Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
- }
- }
- }
-
- public static void Shutdown()
- {
- ApplicationTaskCompletionSource.SetResult(true);
- }
-
- public static void Restart()
- {
- _restartOnShutdown = true;
-
- Shutdown();
- }
-
- private static void StartNewInstance(StartupOptions startupOptions)
- {
- _logger.Info("Starting new instance");
-
- string module = startupOptions.GetOption("-restartpath");
- string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
-
- if (string.IsNullOrWhiteSpace(module))
- {
- module = Environment.GetCommandLineArgs().First();
- }
- if (!startupOptions.ContainsOption("-restartargs"))
- {
- var args = Environment.GetCommandLineArgs()
- .Skip(1)
- .Select(NormalizeCommandLineArgument)
- .ToArray();
-
- commandLineArgsString = string.Join(" ", args);
- }
-
- _logger.Info("Executable: {0}", module);
- _logger.Info("Arguments: {0}", commandLineArgsString);
-
- Process.Start(module, commandLineArgsString);
- }
-
- private static string NormalizeCommandLineArgument(string arg)
- {
- if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
- {
- return arg;
- }
-
- return "\"" + arg + "\"";
- }
- }
-
- // class NoCheckCertificatePolicy : ICertificatePolicy
- // {
- // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
- // {
- // return true;
- // }
- // }
-
- public class MonoEnvironmentInfo : EnvironmentInfo
- {
-
- //public override string GetUserId()
- //{
- // return Syscall.getuid().ToString(CultureInfo.InvariantCulture);
- //}
- }
-}
diff --git a/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs b/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs
deleted file mode 100644
index eda3bcf97..000000000
--- a/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System.Reflection;
-
-// Information about this assembly is defined by the following attributes.
-// Change them to the values specific to your project.
-[assembly: AssemblyTitle ("MediaBrowser.Server.Mono")]
-[assembly: AssemblyDescription ("")]
-[assembly: AssemblyConfiguration ("")]
-[assembly: AssemblyCompany ("")]
-[assembly: AssemblyProduct ("")]
-[assembly: AssemblyCopyright ("Emby")]
-[assembly: AssemblyTrademark ("")]
-[assembly: AssemblyCulture ("")]
-// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
-// The form "{Major}.{Minor}.*" will automatically update the build and revision,
-// and "{Major}.{Minor}.{Build}.*" will update just the revision. \ No newline at end of file
diff --git a/MediaBrowser.Server.Mono/Properties/launchSettings.json b/MediaBrowser.Server.Mono/Properties/launchSettings.json
deleted file mode 100644
index 058ad7adc..000000000
--- a/MediaBrowser.Server.Mono/Properties/launchSettings.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "profiles": {
- "EmbyServer": {
- "commandName": "Project"
- }
- }
-}
diff --git a/MediaBrowser.Tests/M3uParserTest.cs b/MediaBrowser.Tests/M3uParserTest.cs
index 1b42a3823..b5b25b53d 100644
--- a/MediaBrowser.Tests/M3uParserTest.cs
+++ b/MediaBrowser.Tests/M3uParserTest.cs
@@ -6,7 +6,7 @@ using System.Threading.Tasks;
using Emby.Server.Implementations.Cryptography;
using Emby.Server.Implementations.LiveTv.TunerHosts;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MediaBrowser.Tests
diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs
index 8acc490e7..f99103438 100644
--- a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs
+++ b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs
@@ -2,7 +2,7 @@
using System.IO;
using System.Threading;
using Emby.Server.MediaEncoding.Subtitles;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.MediaInfo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -111,4 +111,4 @@ namespace MediaBrowser.Tests.MediaEncoding.Subtitles
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs
index f0c352157..58d02ef04 100644
--- a/MediaBrowser.WebDashboard/Api/DashboardService.cs
+++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using System;
@@ -245,7 +245,7 @@ namespace MediaBrowser.WebDashboard.Api
}
catch (Exception ex)
{
- _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
+ _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name);
return null;
}
})
diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs
index 619d0660f..f510ed51f 100644
--- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs
+++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs
@@ -1,5 +1,5 @@
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
index fb5d39743..855b8b627 100644
--- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
+++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<ItemGroup>
diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs
index e4b11a6fc..dac3f4967 100644
--- a/MediaBrowser.XbmcMetadata/EntryPoint.cs
+++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Configuration;
using MediaBrowser.XbmcMetadata.Savers;
using System;
@@ -72,7 +72,7 @@ namespace MediaBrowser.XbmcMetadata
}
catch (Exception ex)
{
- _logger.ErrorException("Error saving metadata for {0}", ex, item.Path ?? item.Name);
+ _logger.LogError(ex, "Error saving metadata for {path}", item.Path ?? item.Name);
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
index 3fa60fad1..5ffaaed27 100644
--- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
+++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
index 3b8d68776..0aaa0b362 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Configuration;
using MediaBrowser.XbmcMetadata.Savers;
using System;
@@ -294,7 +294,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
}
else
{
- Logger.Warn("Invalid Added value found: " + val);
+ Logger.LogWarning("Invalid Added value found: " + val);
}
}
break;
diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
index ce7b924eb..ce56e080a 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
index 94b4c30f2..e6b4eea1c 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs
@@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Xml;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Xml;
@@ -81,7 +81,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
}
catch (Exception ex)
{
- Logger.ErrorException("Error parsing set node", ex);
+ Logger.LogError(ex, "Error parsing set node");
}
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
index ef1b8ebb2..bcb70ee45 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Globalization;
using System.Xml;
using MediaBrowser.Model.IO;
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
index 570a7fed8..3b46ff7d6 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Xml;
using MediaBrowser.Model.IO;
@@ -91,7 +91,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
}
else
{
- Logger.Info("Unrecognized series status: " + status);
+ Logger.LogInformation("Unrecognized series status: " + status);
}
}
diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
index f56ceed89..e8028f6ad 100644
--- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
index 4fcc222f8..b6b61258b 100644
--- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
index 123c0493f..ae8e638cb 100644
--- a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs
@@ -1,10 +1,10 @@
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.XbmcMetadata.Savers;
-using System.IO;
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
+using MediaBrowser.XbmcMetadata.Savers;
namespace MediaBrowser.XbmcMetadata.Providers
{
@@ -13,7 +13,7 @@ namespace MediaBrowser.XbmcMetadata.Providers
{
protected IFileSystem FileSystem;
- public async Task<MetadataResult<T>> GetMetadata(ItemInfo info,
+ public Task<MetadataResult<T>> GetMetadata(ItemInfo info,
IDirectoryService directoryService,
CancellationToken cancellationToken)
{
@@ -23,7 +23,7 @@ namespace MediaBrowser.XbmcMetadata.Providers
if (file == null)
{
- return result;
+ return Task.FromResult(result);
}
var path = file.FullName;
@@ -44,7 +44,7 @@ namespace MediaBrowser.XbmcMetadata.Providers
result.HasMetadata = false;
}
- return result;
+ return Task.FromResult(result);
}
protected abstract void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken);
diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
index eeb55d8bc..c7ff55323 100644
--- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using MediaBrowser.XbmcMetadata.Savers;
using System.Linq;
@@ -54,4 +54,4 @@ namespace MediaBrowser.XbmcMetadata.Providers
.FirstOrDefault(i => i != null);
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
index 3bc10f35b..6883048f6 100644
--- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using System.Collections.Generic;
using System.IO;
diff --git a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
index 031bdc8d2..1e4ccbe38 100644
--- a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Xml;
namespace MediaBrowser.XbmcMetadata.Providers
@@ -30,4 +30,4 @@ namespace MediaBrowser.XbmcMetadata.Providers
{
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
index 0d214f58d..ddd32512a 100644
--- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
index 368d37e0a..34a7a088e 100644
--- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
+++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs
@@ -1,7 +1,7 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Parsers;
using System.IO;
using System.Threading;
diff --git a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
index dcce00d69..54d0b8bae 100644
--- a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
diff --git a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
index f571dc2b7..cc0da1b36 100644
--- a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Configuration;
using System.Collections.Generic;
using System.Globalization;
@@ -91,4 +91,4 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
index f6ea9b4b2..2b550193f 100644
--- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
@@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Configuration;
using System;
using System.Collections.Generic;
@@ -230,7 +230,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
catch (Exception ex)
{
- Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message);
+ Logger.LogError(ex, "Error setting hidden attribute on {path}", path);
}
}
@@ -283,7 +283,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
catch (XmlException ex)
{
- Logger.ErrorException("Error reading existng nfo", ex);
+ Logger.LogError(ex, "Error reading existing nfo");
}
writer.WriteEndElement();
@@ -353,7 +353,8 @@ namespace MediaBrowser.XbmcMetadata.Savers
if (!string.IsNullOrEmpty(stream.Language))
{
- // https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify
+ // http://web.archive.org/web/20181230211547/https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify
+ // Web Archive version of link since it's not really explained in the thread.
writer.WriteElementString("language", RemoveInvalidXMLChars(stream.Language));
}
@@ -774,9 +775,9 @@ namespace MediaBrowser.XbmcMetadata.Savers
try
{
var tagName = GetTagForProviderKey(providerKey);
- //Logger.Debug("Verifying custom provider tagname {0}", tagName);
+ //logger.LogDebug("Verifying custom provider tagname {0}", tagName);
XmlConvert.VerifyName(tagName);
- //Logger.Debug("Saving custom provider tagname {0}", tagName);
+ //logger.LogDebug("Saving custom provider tagname {0}", tagName);
writer.WriteElementString(GetTagForProviderKey(providerKey), providerId);
}
@@ -1000,7 +1001,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
}
catch (Exception ex)
{
- logger.ErrorException("Error reading existing xml tags from {0}.", ex, path);
+ logger.LogError(ex, "Error reading existing xml tags from {path}.", path);
return;
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
index 33f96fc8f..d1f30b1fe 100644
--- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.XbmcMetadata.Configuration;
using System.Collections.Generic;
using System.Globalization;
@@ -115,4 +115,4 @@ namespace MediaBrowser.XbmcMetadata.Savers
{
}
}
-} \ No newline at end of file
+}
diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
index 0fc74e66b..c703a9ea6 100644
--- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs
@@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Xml;
diff --git a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
index 5a626eef9..50ae8d24e 100644
--- a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs
@@ -2,7 +2,7 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
index 27bc5f038..e0f08dbdb 100644
--- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
diff --git a/MediaBrowser.sln b/MediaBrowser.sln
index 1f4b01b31..13d1e26db 100644
--- a/MediaBrowser.sln
+++ b/MediaBrowser.sln
@@ -3,13 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.3
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{E60FB157-87E2-4A41-8B04-27EA49B63B4D}"
- ProjectSection(SolutionItems) = preProject
- .nuget\NuGet.Config = .nuget\NuGet.Config
- .nuget\NuGet.exe = .nuget\NuGet.exe
- .nuget\NuGet.targets = .nuget\NuGet.targets
- EndProjectSection
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Controller", "MediaBrowser.Controller\MediaBrowser.Controller.csproj", "{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Api", "MediaBrowser.Api\MediaBrowser.Api.csproj", "{4FD51AC5-2C16-4308-A993-C3A84F3B4582}"
@@ -28,8 +21,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.XbmcMetadata",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.LocalMetadata", "MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj", "{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EmbyServer", "MediaBrowser.Server.Mono\EmbyServer.csproj", "{175A9388-F352-4586-A6B4-070DED62B644}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Photos", "Emby.Photos\Emby.Photos.csproj", "{89AB4548-770D-41FD-A891-8DAFF44F452C}"
@@ -44,8 +35,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RSSDP", "RSSDP\RSSDP.csproj
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Dlna", "Emby.Dlna\Emby.Dlna.csproj", "{805844AB-E92F-45E6-9D99-4F6D48D129A5}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing.ImageMagick", "Emby.Drawing.ImageMagick\Emby.Drawing.ImageMagick.csproj", "{6CFEE013-6E7C-432B-AC37-CABF0880C69A}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing.Skia", "Emby.Drawing.Skia\Emby.Drawing.Skia.csproj", "{2312DA6D-FF86-4597-9777-BCEEC32D96DD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.Nat", "Mono.Nat\Mono.Nat.csproj", "{CB7F2326-6497-4A3D-BA03-48513B17A7BE}"
@@ -56,517 +45,127 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Notifications", "Emby.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Naming", "Emby.Naming\Emby.Naming.csproj", "{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageMagickSharp", "ImageMagickSharp\ImageMagickSharp\ImageMagickSharp.csproj", "{124E0710-6572-497B-B2A5-696AA08AD8BB}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "taglib-sharp", "ThirdParty\taglib-sharp\src\taglib-sharp.csproj", "{D45FC504-D06B-41A0-A220-C20B7E8F1304}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "taglib-sharp", "ThirdParty\taglib-sharp\src\taglib-sharp.csproj", "{D45FC504-D06B-41A0-A220-C20B7E8F1304}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj", "{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj", "{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IsoMounter", "Emby.IsoMounting\IsoMounter\IsoMounter.csproj", "{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IsoMounter", "Emby.IsoMounting\IsoMounter\IsoMounter.csproj", "{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
- Debug|Mixed Platforms = Debug|Mixed Platforms
- Debug|Win32 = Debug|Win32
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
- Release|Mixed Platforms = Release|Mixed Platforms
- Release|Win32 = Release|Win32
- Release|x64 = Release|x64
- Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x64.ActiveCfg = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x86.ActiveCfg = Debug|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x86.Build.0 = Debug|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.Build.0 = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Win32.ActiveCfg = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x64.ActiveCfg = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x86.ActiveCfg = Release|Any CPU
- {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x86.Build.0 = Release|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x64.ActiveCfg = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x86.ActiveCfg = Debug|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x86.Build.0 = Debug|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.Build.0 = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Win32.ActiveCfg = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x64.ActiveCfg = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x86.ActiveCfg = Release|Any CPU
- {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x86.Build.0 = Release|Any CPU
{9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x64.ActiveCfg = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x86.ActiveCfg = Debug|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x86.Build.0 = Debug|Any CPU
{9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.Build.0 = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Win32.ActiveCfg = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x64.ActiveCfg = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x86.ActiveCfg = Release|Any CPU
- {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x86.Build.0 = Release|Any CPU
{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x86.Build.0 = Debug|Any CPU
{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.Build.0 = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Win32.ActiveCfg = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x64.ActiveCfg = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x86.ActiveCfg = Release|Any CPU
- {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x86.Build.0 = Release|Any CPU
{5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x64.ActiveCfg = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x86.ActiveCfg = Debug|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x86.Build.0 = Debug|Any CPU
{5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.Build.0 = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Win32.ActiveCfg = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x64.ActiveCfg = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x86.ActiveCfg = Release|Any CPU
- {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x86.Build.0 = Release|Any CPU
{442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|x86.ActiveCfg = Debug|Any CPU
{442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.Build.0 = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Win32.ActiveCfg = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|x64.ActiveCfg = Release|Any CPU
- {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|x86.ActiveCfg = Release|Any CPU
{4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|x64.ActiveCfg = Debug|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|x86.ActiveCfg = Debug|Any CPU
{4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.Build.0 = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Win32.ActiveCfg = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|x64.ActiveCfg = Release|Any CPU
- {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|x86.ActiveCfg = Release|Any CPU
{23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|x64.ActiveCfg = Debug|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Debug|x86.ActiveCfg = Debug|Any CPU
{23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.Build.0 = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|Win32.ActiveCfg = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|x64.ActiveCfg = Release|Any CPU
- {23499896-B135-4527-8574-C26E926EA99E}.Release|x86.ActiveCfg = Release|Any CPU
{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|x64.ActiveCfg = Debug|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|x86.ActiveCfg = Debug|Any CPU
{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.Build.0 = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Win32.ActiveCfg = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x64.ActiveCfg = Release|Any CPU
- {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x86.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Win32.Build.0 = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x64.ActiveCfg = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x86.ActiveCfg = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x86.Build.0 = Debug|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|Win32.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|Win32.Build.0 = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|x64.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|x86.ActiveCfg = Release|Any CPU
- {175A9388-F352-4586-A6B4-070DED62B644}.Release|x86.Build.0 = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|x64.ActiveCfg = Debug|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|x86.ActiveCfg = Debug|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.ActiveCfg = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.Build.0 = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Win32.ActiveCfg = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x64.ActiveCfg = Release|Any CPU
- {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x86.ActiveCfg = Release|Any CPU
{89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Win32.Build.0 = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x64.ActiveCfg = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x64.Build.0 = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x86.ActiveCfg = Debug|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x86.Build.0 = Debug|Any CPU
{89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.Build.0 = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Win32.ActiveCfg = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Win32.Build.0 = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x64.ActiveCfg = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x64.Build.0 = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x86.ActiveCfg = Release|Any CPU
- {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x86.Build.0 = Release|Any CPU
{713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Win32.Build.0 = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x64.ActiveCfg = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x64.Build.0 = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x86.ActiveCfg = Debug|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x86.Build.0 = Debug|Any CPU
{713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.Build.0 = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Win32.ActiveCfg = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Win32.Build.0 = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x64.ActiveCfg = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x64.Build.0 = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x86.ActiveCfg = Release|Any CPU
- {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x86.Build.0 = Release|Any CPU
{88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Win32.Build.0 = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x64.ActiveCfg = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x64.Build.0 = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x86.ActiveCfg = Debug|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x86.Build.0 = Debug|Any CPU
{88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.Build.0 = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Win32.ActiveCfg = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Win32.Build.0 = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x64.ActiveCfg = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x64.Build.0 = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x86.ActiveCfg = Release|Any CPU
- {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x86.Build.0 = Release|Any CPU
{E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Win32.Build.0 = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x64.ActiveCfg = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x64.Build.0 = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x86.ActiveCfg = Debug|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x86.Build.0 = Debug|Any CPU
{E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.Build.0 = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Win32.ActiveCfg = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Win32.Build.0 = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x64.ActiveCfg = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x64.Build.0 = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x86.ActiveCfg = Release|Any CPU
- {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x86.Build.0 = Release|Any CPU
{21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Win32.Build.0 = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x64.ActiveCfg = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x64.Build.0 = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x86.ActiveCfg = Debug|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x86.Build.0 = Debug|Any CPU
{21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.Build.0 = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Win32.ActiveCfg = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Win32.Build.0 = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x64.ActiveCfg = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x64.Build.0 = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x86.ActiveCfg = Release|Any CPU
- {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x86.Build.0 = Release|Any CPU
{805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Win32.Build.0 = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x64.ActiveCfg = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x64.Build.0 = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x86.ActiveCfg = Debug|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x86.Build.0 = Debug|Any CPU
{805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.Build.0 = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Win32.ActiveCfg = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Win32.Build.0 = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x64.ActiveCfg = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x64.Build.0 = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x86.ActiveCfg = Release|Any CPU
- {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x86.Build.0 = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Win32.Build.0 = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x64.ActiveCfg = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x64.Build.0 = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x86.ActiveCfg = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x86.Build.0 = Debug|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Any CPU.Build.0 = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Win32.ActiveCfg = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Win32.Build.0 = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x64.ActiveCfg = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x64.Build.0 = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x86.ActiveCfg = Release|Any CPU
- {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x86.Build.0 = Release|Any CPU
{2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Win32.Build.0 = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x64.ActiveCfg = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x64.Build.0 = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x86.ActiveCfg = Debug|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x86.Build.0 = Debug|Any CPU
{2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Any CPU.Build.0 = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Win32.ActiveCfg = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Win32.Build.0 = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x64.ActiveCfg = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x64.Build.0 = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x86.ActiveCfg = Release|Any CPU
- {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x86.Build.0 = Release|Any CPU
{CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Win32.Build.0 = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x64.ActiveCfg = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x64.Build.0 = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x86.ActiveCfg = Debug|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x86.Build.0 = Debug|Any CPU
{CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.Build.0 = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Win32.ActiveCfg = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Win32.Build.0 = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x64.ActiveCfg = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x64.Build.0 = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x86.ActiveCfg = Release|Any CPU
- {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x86.Build.0 = Release|Any CPU
{1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Win32.Build.0 = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x64.ActiveCfg = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x64.Build.0 = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x86.ActiveCfg = Debug|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x86.Build.0 = Debug|Any CPU
{1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.Build.0 = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Win32.ActiveCfg = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Win32.Build.0 = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x64.ActiveCfg = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x64.Build.0 = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x86.ActiveCfg = Release|Any CPU
- {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x86.Build.0 = Release|Any CPU
{2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Win32.Build.0 = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x64.ActiveCfg = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x64.Build.0 = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x86.ActiveCfg = Debug|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x86.Build.0 = Debug|Any CPU
{2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.Build.0 = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Win32.ActiveCfg = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Win32.Build.0 = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x64.ActiveCfg = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x64.Build.0 = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x86.ActiveCfg = Release|Any CPU
- {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x86.Build.0 = Release|Any CPU
{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Win32.Build.0 = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x64.ActiveCfg = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x64.Build.0 = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x86.ActiveCfg = Debug|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x86.Build.0 = Debug|Any CPU
{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.Build.0 = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Win32.ActiveCfg = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Win32.Build.0 = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x64.ActiveCfg = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x64.Build.0 = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x86.ActiveCfg = Release|Any CPU
- {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x86.Build.0 = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Win32.Build.0 = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x64.ActiveCfg = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x64.Build.0 = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x86.ActiveCfg = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x86.Build.0 = Debug|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Any CPU.Build.0 = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Win32.ActiveCfg = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Win32.Build.0 = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x64.ActiveCfg = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x64.Build.0 = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x86.ActiveCfg = Release|Any CPU
- {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x86.Build.0 = Release|Any CPU
{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Win32.Build.0 = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x64.Build.0 = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x86.Build.0 = Debug|Any CPU
{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.Build.0 = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Win32.ActiveCfg = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Win32.Build.0 = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x64.ActiveCfg = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x64.Build.0 = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x86.ActiveCfg = Release|Any CPU
- {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x86.Build.0 = Release|Any CPU
{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Win32.Build.0 = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x64.ActiveCfg = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x64.Build.0 = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x86.ActiveCfg = Debug|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x86.Build.0 = Debug|Any CPU
{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.Build.0 = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Win32.ActiveCfg = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Win32.Build.0 = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x64.ActiveCfg = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x64.Build.0 = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x86.ActiveCfg = Release|Any CPU
- {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x86.Build.0 = Release|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Win32.ActiveCfg = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Win32.Build.0 = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x64.ActiveCfg = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x64.Build.0 = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x86.ActiveCfg = Debug|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x86.Build.0 = Debug|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Win32.ActiveCfg = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Win32.Build.0 = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x64.ActiveCfg = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x64.Build.0 = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.ActiveCfg = Release|Any CPU
- {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.Build.0 = Release|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -574,4 +173,22 @@ Global
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE}
EndGlobalSection
+ GlobalSection(AutomaticVersions) = postSolution
+ UpdateAssemblyVersion = True
+ UpdateAssemblyFileVersion = True
+ UpdateAssemblyInfoVersion = True
+ AssemblyVersionSettings = None.None.None.None
+ AssemblyFileVersionSettings = None.None.None.None
+ AssemblyInfoVersionSettings = None.None.None.None
+ UpdatePackageVersion = False
+ AssemblyInfoVersionType = SettingsVersion
+ InheritWinAppVersionFrom = None
+ EndGlobalSection
+ GlobalSection(MonoDevelopProperties) = preSolution
+ Policies = $0
+ $0.StandardHeader = $1
+ $1.Text = @### This header should be used to start new files.\n### It provides an explicit per-file license reference that should be present on all new files.\n### To use this header, delete these lines and the following empty line, modify <filename> to\n### the proper full path, and then add new code following the header and a single empty line.\n\n// ${FileName}\n// Part of the Jellyfin project (https://jellyfin.media)\n//\n// All copyright belongs to the Jellyfin contributors; a full list can\n// be found in the file CONTRIBUTORS.md\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, version 2.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n
+ $0.DotNetNamingPolicy = $2
+ $2.DirectoryNamespaceAssociation = PrefixedHierarchical
+ EndGlobalSection
EndGlobal
diff --git a/Mono.Nat/Mono.Nat.csproj b/Mono.Nat/Mono.Nat.csproj
index eacf84c35..26028eca9 100644
--- a/Mono.Nat/Mono.Nat.csproj
+++ b/Mono.Nat/Mono.Nat.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/Mono.Nat/NatManager.cs b/Mono.Nat/NatManager.cs
index 752fd0416..3ed01a6b3 100644
--- a/Mono.Nat/NatManager.cs
+++ b/Mono.Nat/NatManager.cs
@@ -4,7 +4,7 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Linq;
namespace Mono.Nat
diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs
index dc0e2c89b..fbf3032d4 100644
--- a/Mono.Nat/Pmp/PmpNatDevice.cs
+++ b/Mono.Nat/Pmp/PmpNatDevice.cs
@@ -32,7 +32,7 @@ using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
using MediaBrowser.Model.Extensions;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Mono.Nat.Pmp
{
@@ -132,7 +132,7 @@ namespace Mono.Nat.Pmp
mapping.Protocol,
mapping.PrivatePort,
e.Message);
- _logger.Debug(message);
+ _logger.LogDebug(message);
throw e;
}
@@ -183,7 +183,7 @@ namespace Mono.Nat.Pmp
};
var errorMsg = errors[resultCode];
- _logger.Debug("Error in CreatePortMapListen: " + errorMsg);
+ _logger.LogDebug("Error in CreatePortMapListen: " + errorMsg);
return;
}
@@ -198,7 +198,7 @@ namespace Mono.Nat.Pmp
}
catch (Exception ex)
{
- _logger.ErrorException("Error in CreatePortMapListen", ex);
+ _logger.LogError(ex, "Error in CreatePortMapListen");
return;
}
}
diff --git a/Mono.Nat/Pmp/PmpSearcher.cs b/Mono.Nat/Pmp/PmpSearcher.cs
index 180fb48d7..98cf37f14 100644
--- a/Mono.Nat/Pmp/PmpSearcher.cs
+++ b/Mono.Nat/Pmp/PmpSearcher.cs
@@ -37,7 +37,7 @@ using Mono.Nat.Pmp;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using System.Linq;
namespace Mono.Nat
@@ -208,7 +208,7 @@ namespace Mono.Nat
return;
int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
if (errorcode != 0)
- _logger.Debug("Non zero error: {0}", errorcode);
+ _logger.LogDebug("Non zero error: {0}", errorcode);
IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
nextSearch = DateTime.Now.AddMinutes(5);
diff --git a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
index 3395b7596..4b765fd42 100644
--- a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
+++ b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
@@ -28,7 +28,7 @@ using System;
using System.Diagnostics;
using System.Net;
using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace Mono.Nat.Upnp
{
@@ -42,10 +42,10 @@ namespace Mono.Nat.Upnp
: base(null)
{
if (string.IsNullOrEmpty(description))
- _logger.Warn("Description is null");
+ _logger.LogWarning("Description is null");
if (hostAddress == null)
- _logger.Warn("hostaddress is null");
+ _logger.LogWarning("hostaddress is null");
this.servicesDescriptionUrl = description;
this.hostAddress = hostAddress;
diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
index 7c1e89d3b..bcf358d1c 100644
--- a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
+++ b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
@@ -37,7 +37,7 @@ using System.Diagnostics;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Dlna;
using System.Threading.Tasks;
@@ -90,7 +90,7 @@ namespace Mono.Nat
}
catch (Exception ex)
{
- _logger.ErrorException("Error decoding device response", ex);
+ _logger.LogError(ex, "Error decoding device response");
}
}
diff --git a/Mono.Nat/Upnp/UpnpNatDevice.cs b/Mono.Nat/Upnp/UpnpNatDevice.cs
index cae7f5fc8..62539103a 100644
--- a/Mono.Nat/Upnp/UpnpNatDevice.cs
+++ b/Mono.Nat/Upnp/UpnpNatDevice.cs
@@ -34,7 +34,7 @@ using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Dlna;
namespace Mono.Nat.Upnp
@@ -77,7 +77,7 @@ namespace Mono.Nat.Upnp
// Are we going to get addresses with the "http://" attached?
if (locationDetails.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
{
- _logger.Debug("Found device at: {0}", locationDetails);
+ _logger.LogDebug("Found device at: {0}", locationDetails);
// This bit strings out the "http://" from the string
locationDetails = locationDetails.Substring(7);
@@ -89,7 +89,7 @@ namespace Mono.Nat.Upnp
}
else
{
- _logger.Debug("Couldn't decode address. Please send following string to the developer: ");
+ _logger.LogDebug("Couldn't decode address. Please send following string to the developer: ");
}
}
@@ -116,7 +116,7 @@ namespace Mono.Nat.Upnp
{
if (response.StatusCode != HttpStatusCode.OK)
{
- _logger.Debug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
+ _logger.LogDebug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
return; // FIXME: This the best thing to do??
}
@@ -139,7 +139,7 @@ namespace Mono.Nat.Upnp
{
return;
}
- _logger.Debug("{0}: Couldn't parse services list", HostEndPoint);
+ _logger.LogDebug("{0}: Couldn't parse services list", HostEndPoint);
System.Threading.Thread.Sleep(10);
}
}
@@ -155,14 +155,14 @@ namespace Mono.Nat.Upnp
{
//If the service is a WANIPConnection, then we have what we want
string type = service["serviceType"].InnerText;
- _logger.Debug("{0}: Found service: {1}", HostEndPoint, type);
+ _logger.LogDebug("{0}: Found service: {1}", HostEndPoint, type);
// TODO: Add support for version 2 of UPnP.
if (string.Equals(type, "urn:schemas-upnp-org:service:WANPPPConnection:1", StringComparison.OrdinalIgnoreCase) ||
string.Equals(type, "urn:schemas-upnp-org:service:WANIPConnection:1", StringComparison.OrdinalIgnoreCase))
{
this.controlUrl = service["controlURL"].InnerText;
- _logger.Debug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
+ _logger.LogDebug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
Uri u;
if (Uri.TryCreate(controlUrl, UriKind.RelativeOrAbsolute, out u))
@@ -174,15 +174,15 @@ namespace Mono.Nat.Upnp
if (IPAddress.TryParse(u.Host, out parsedHostIpAddress))
{
this.hostEndPoint = new IPEndPoint(parsedHostIpAddress, u.Port);
- //_logger.Debug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
+ //_logger.LogDebug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
- //_logger.Debug("{0}: New control url: {1}", HostEndPoint, controlUrl);
+ //_logger.LogDebug("{0}: New control url: {1}", HostEndPoint, controlUrl);
}
}
}
else
{
- _logger.Debug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
+ _logger.LogDebug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
}
return;
}
@@ -266,4 +266,4 @@ namespace Mono.Nat.Upnp
this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen);
}
}
-} \ No newline at end of file
+}
diff --git a/README.md b/README.md
index c4133eb9d..dfa8457de 100644
--- a/README.md
+++ b/README.md
@@ -1,53 +1,36 @@
<h1 align="center">Jellyfin</h1>
<h3 align="center">The Free Software Media System</h3>
-<p align="center">
-Jellyfin is a free software media system that puts you in control of managing and streaming your media.
-</p>
-
------
-
-<p align="center">
-<strong>Want to get started?</strong> Choose from <a href="https://github.com/jellyfin/jellyfin/wiki/Prebuilt-Packages">Prebuilt Packages</a>, or <a href="https://github.com/jellyfin/jellyfin/wiki/Building-from-Source">Build from Source</a>.
-</p>
-<p align="center">
-<strong>Want to contribute?</strong> Check out <a href="https://github.com/jellyfin/jellyfin/wiki/Contributing-to-Jellyfin">our wiki for guidelines</a>.
-</p>
-
---
<p align="center">
+<img alt="Logo banner" src="https://raw.githubusercontent.com/jellyfin/jellyfin-ux/master/branding/SVG/banner-logo-solid.svg?sanitize=true"/>
+<br/></br>
<a href="https://github.com/jellyfin/jellyfin"><img alt="GPL 2.0 License" src="https://img.shields.io/github/license/jellyfin/jellyfin.svg"></a>
<a href="https://cloud.drone.io/jellyfin/jellyfin"><img alt="Build Status" src="https://cloud.drone.io/api/badges/jellyfin/jellyfin/status.svg"></a>
<a href="https://hub.docker.com/r/jellyfin/jellyfin"><img alt="Docker Pull Count" src="https://img.shields.io/docker/pulls/jellyfin/jellyfin.svg"></a>
-<a href="https://matrix.to/#/#jellyfin:matrix.org"><img alt="Chat on Matrix" src="https://img.shields.io/matrix/jellyfin:matrix.org.svg?logo=matrix"></a>
+<a href="https://jellyfin.readthedocs.io"><img alt="Documentation" src="https://img.shields.io/readthedocs/jellyfin.svg"></a>
+<a href="https://matrix.to/#/+jellyfin:matrix.org"><img alt="Chat on Matrix" src="https://img.shields.io/matrix/jellyfin:matrix.org.svg?logo=matrix"></a>
<a href="https://www.reddit.com/r/jellyfin/"><img alt="Join our Subreddit" src="https://img.shields.io/badge/reddit-r%2Fjellyfin-%23FF5700.svg"></a>
</p>
-For further details, please see [our wiki](https://github.com/jellyfin/jellyfin/wiki).
-
-To receive the latest updates, please visit [our public chat on Matrix/Riot](https://matrix.to/#/#jellyfin:matrix.org), our [announce chat](https://matrix.to/#/#jellyfin-announce:matrix.org) for release info, and follow us on [Social Media](https://github.com/jellyfin/jellyfin/wiki/Social-Media).
-
-## About
-
-The Jellyfin project was started as a result of Emby's decision to take their code closed-source, as well as various philosophical differences with the core developers. Jellyfin seeks to be the free software alternative to Emby and Plex to provide media management and streaming from a dedicated server to end-user devices.
-
-Jellyfin is descended from Emby 3.5.2, ported to the .NET Core framework, and aims to contain build facilities for every platform.
+---
-## Issues and Feature Requests
+Jellyfin is a Free Software Media System that puts you in control of managing and streaming your media. It is an alternative to the proprietary Emby and Plex, to provide media from a dedicated server to end-user devices via multiple apps. Jellyfin is descended from Emby's 3.5.2 release and ported to the .NET Core framework to enable full cross-platform support. There are no strings attached, no premium licenses or features, and no hidden agendas: just a team who want to build something better and work together to achieve it. We welcome anyone who is interested in joining us in our quest!
+For further details, please see [our documentation page](https://jellyfin.readthedocs.io). To receive the latest updates, get help with Jellyfin, and join the community, please visit [one of our communication channels on Matrix/Riot or social media](https://jellyfin.readthedocs.io/en/latest/user-docs/getting-help).
+For more information about the project, please see our [about page](https://jellyfin.readthedocs.io/en/latest/about/).
<p align="center">
- <strong>New idea or improvement?</strong>
-<em>Open a <a href="https://github.com/jellyfin/jellyfin/wiki/Feature-Requests">Feature Request</a>.</em>
+<strong>Want to get started?</strong>
+<em>Choose from <a href="https://jellyfin.readthedocs.io/en/latest/user-docs/installing/">Prebuilt Packages</a> or <a href="https://jellyfin.readthedocs.io/en/latest/user-docs/building/">Build from Source</a>, then see our <a href="https://jellyfin.readthedocs.io/en/latest/user-docs/quick-start/">Quickstart guide</a>.</em>
</p>
<p align="center">
- <Strong>Something not working right?</strong>
-<em>Open an <a href="https://github.com/jellyfin/jellyfin/wiki/Issue-Guidelines">Issue</a>.</em>
+<strong>Want to contribute?</strong>
+<em>Check out <a href="https://jellyfin.readthedocs.io/en/latest/developer-docs/contributing/">our documentation for guidelines</a>.</em>
+</p>
+<p align="center">
+<strong>New idea or improvement? Something not working right?</strong>
+<em>Open an <a href="https://jellyfin.readthedocs.io/en/latest/developer-docs/issues/">Issue</a>.</em>
</p>
-
-
-## Contributing to Jellyfin
-
-If you're interested in contributing, please see [our wiki for guidelines](https://github.com/jellyfin/jellyfin/wiki/Contributing-to-Jellyfin).
diff --git a/RSSDP/LICENSE b/RSSDP/LICENSE
new file mode 100644
index 000000000..aabeb93af
--- /dev/null
+++ b/RSSDP/LICENSE
@@ -0,0 +1,4 @@
+RSSDP
+
+Copyright (c) 2015 Troy Willmot
+Copyright (c) 2015-2018 Luke Pulverenti
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs
index bc8594649..65ec0ca71 100644
--- a/RSSDP/SsdpCommunicationsServer.cs
+++ b/RSSDP/SsdpCommunicationsServer.cs
@@ -7,7 +7,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
namespace Rssdp.Infrastructure
@@ -131,7 +131,7 @@ namespace Rssdp.Infrastructure
}
catch (Exception ex)
{
- _logger.ErrorException("Error in BeginListeningForBroadcasts", ex);
+ _logger.LogError(ex, "Error in BeginListeningForBroadcasts");
}
}
}
@@ -148,7 +148,7 @@ namespace Rssdp.Infrastructure
{
if (_BroadcastListenSocket != null)
{
- _logger.Info("{0} disposing _BroadcastListenSocket.", GetType().Name);
+ _logger.LogInformation("{0} disposing _BroadcastListenSocket.", GetType().Name);
_BroadcastListenSocket.Dispose();
_BroadcastListenSocket = null;
}
@@ -197,7 +197,7 @@ namespace Rssdp.Infrastructure
}
catch (Exception ex)
{
- _logger.ErrorException("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString());
+ _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString());
}
}
@@ -282,11 +282,11 @@ namespace Rssdp.Infrastructure
var sockets = _sendSockets.ToList();
_sendSockets = null;
- _logger.Info("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count);
+ _logger.LogInformation("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count);
foreach (var socket in sockets)
{
- _logger.Info("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress);
+ _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress);
socket.Dispose();
}
}
@@ -376,7 +376,7 @@ namespace Rssdp.Infrastructure
}
catch (Exception ex)
{
- _logger.ErrorException("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address);
+ _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address);
}
}
}
@@ -508,4 +508,4 @@ namespace Rssdp.Infrastructure
#endregion
}
-} \ No newline at end of file
+}
diff --git a/SharedVersion.cs b/SharedVersion.cs
index 379b5b43c..791d6cac5 100644
--- a/SharedVersion.cs
+++ b/SharedVersion.cs
@@ -1,3 +1,3 @@
using System.Reflection;
-[assembly: AssemblyVersion("3.5.2.0")]
+[assembly: AssemblyVersion("10.0.0")]
diff --git a/SocketHttpListener/Net/HttpConnection.cs b/SocketHttpListener/Net/HttpConnection.cs
index 9b4fb8705..4fc9a468c 100644
--- a/SocketHttpListener/Net/HttpConnection.cs
+++ b/SocketHttpListener/Net/HttpConnection.cs
@@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
@@ -173,7 +173,7 @@ namespace SocketHttpListener.Net
private void OnTimeout(object unused)
{
- //_logger.Info("HttpConnection timer fired");
+ //_logger.LogInformation("HttpConnection timer fired");
CloseSocket();
Unbind();
}
@@ -556,4 +556,4 @@ namespace SocketHttpListener.Net
}
}
}
-} \ No newline at end of file
+}
diff --git a/SocketHttpListener/Net/HttpEndPointListener.cs b/SocketHttpListener/Net/HttpEndPointListener.cs
index 254e76140..fb093314c 100644
--- a/SocketHttpListener/Net/HttpEndPointListener.cs
+++ b/SocketHttpListener/Net/HttpEndPointListener.cs
@@ -8,7 +8,7 @@ using System.Security.Cryptography.X509Certificates;
using System.Threading;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
@@ -173,7 +173,7 @@ namespace SocketHttpListener.Net
{
HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken;
- epl._logger.ErrorException("Error in socket.AcceptAsync", ex);
+ epl._logger.LogError(ex, "Error in socket.AcceptAsync");
}
}
@@ -204,7 +204,7 @@ namespace SocketHttpListener.Net
if (socketError == SocketError.ConnectionReset)
{
- epl._logger.Error("SocketError.ConnectionReset reported. Attempting to re-accept.");
+ epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept.");
return;
}
@@ -223,13 +223,13 @@ namespace SocketHttpListener.Net
{
var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString();
var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString();
- //_logger.Info("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
+ //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure);
HttpConnection conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment);
await conn.Init().ConfigureAwait(false);
- //_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
+ //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
lock (epl._unregisteredConnections)
{
epl._unregisteredConnections[conn] = conn;
@@ -238,7 +238,7 @@ namespace SocketHttpListener.Net
}
catch (Exception ex)
{
- epl._logger.ErrorException("Error in ProcessAccept", ex);
+ epl._logger.LogError(ex, "Error in ProcessAccept");
TryClose(accepted);
epl.Accept();
diff --git a/SocketHttpListener/Net/HttpEndPointManager.cs b/SocketHttpListener/Net/HttpEndPointManager.cs
index 45af92c01..01b5ae9bd 100644
--- a/SocketHttpListener/Net/HttpEndPointManager.cs
+++ b/SocketHttpListener/Net/HttpEndPointManager.cs
@@ -6,7 +6,7 @@ using System.Net.Sockets;
using System.Reflection;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using SocketHttpListener.Primitives;
diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs
index 759be64c9..941b99f35 100644
--- a/SocketHttpListener/Net/HttpListener.cs
+++ b/SocketHttpListener/Net/HttpListener.cs
@@ -7,7 +7,7 @@ using System.Security.Cryptography.X509Certificates;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
@@ -58,11 +58,6 @@ namespace SocketHttpListener.Net
auth_schemes = AuthenticationSchemes.Anonymous;
}
- public HttpListener(X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo)
- :this(new NullLogger(), certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo)
- {
- }
-
public HttpListener(ILogger logger, X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo)
: this(logger, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo)
{
diff --git a/SocketHttpListener/Net/HttpListenerContext.cs b/SocketHttpListener/Net/HttpListenerContext.cs
index b90f07567..0aaac1ad5 100644
--- a/SocketHttpListener/Net/HttpListenerContext.cs
+++ b/SocketHttpListener/Net/HttpListenerContext.cs
@@ -1,6 +1,10 @@
using System;
using System.Net;
using System.Security.Principal;
+using MediaBrowser.Model.Cryptography;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
+using MediaBrowser.Model.Text;
using SocketHttpListener.Net.WebSockets;
using System.Threading.Tasks;
diff --git a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs
index 53efcb0fa..ed99af1a6 100644
--- a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs
+++ b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
namespace SocketHttpListener.Net
{
diff --git a/SocketHttpListener/Net/HttpResponseStream.Managed.cs b/SocketHttpListener/Net/HttpResponseStream.Managed.cs
index 1a8a195fb..e727f1b4a 100644
--- a/SocketHttpListener/Net/HttpResponseStream.Managed.cs
+++ b/SocketHttpListener/Net/HttpResponseStream.Managed.cs
@@ -8,7 +8,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Logging;
+using Microsoft.Extensions.Logging;
using MediaBrowser.Model.System;
namespace SocketHttpListener.Net
diff --git a/SocketHttpListener/SocketHttpListener.csproj b/SocketHttpListener/SocketHttpListener.csproj
index 494bc7fc9..ca9056a6a 100644
--- a/SocketHttpListener/SocketHttpListener.csproj
+++ b/SocketHttpListener/SocketHttpListener.csproj
@@ -6,7 +6,7 @@
</ItemGroup>
<ItemGroup>
- <Compile Include="..\SharedVersion.cs"/>
+ <Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<PropertyGroup>
diff --git a/build-jellyfin.ps1 b/build-jellyfin.ps1
index 5544df88a..224716621 100644
--- a/build-jellyfin.ps1
+++ b/build-jellyfin.ps1
@@ -103,7 +103,7 @@ if($InstallNSSM.IsPresent -or ($InstallNSSM -eq $true)){
Install-NSSM $InstallLocation $Architecture
}
Copy-Item .\install-jellyfin.ps1 $InstallLocation\install-jellyfin.ps1
-Copy-Item .\installjellyfin.bat $InstallLocation\installjellyfin.bat
+Copy-Item .\install.bat $InstallLocation\install.bat
if($GenerateZip.IsPresent -or ($GenerateZip -eq $true)){
Compress-Archive -Path $InstallLocation -DestinationPath "$InstallLocation/jellyfin.zip" -Force
}
diff --git a/debian/changelog b/debian/changelog
index 9dc21d467..61223e725 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,13 @@
+jellyfin (10.0.0-1) unstable; urgency=medium
+
+ * The first Jellyfin release under our new versioning scheme
+ * Numerous bugfixes and code readability improvements
+ * Updated logging configuration, including flag for it and configdir
+ * Updated theming including logo
+ * Dozens of other improvements as documented in GitHub pull request #419
+
+ -- Joshua Boniface <joshua@boniface.me> Sat, 05 Jan 2019 15:39:25 -0500
+
jellyfin (3.5.2-5) unstable; urgency=medium
* Fully GPL'd release - remove tainted code from MediaBrowser.Common
@@ -34,16 +44,3 @@ jellyfin (3.5.2) unstable; urgency=medium
* Rename from emby-server on version 3.5.2
-- Joshua Boniface <joshua@boniface.me> Sun, 9 Dec 2018 15:20:58 -0400
-
-emby-server (3.5.2-unlocked) unstable; urgency=medium
-
- * Taking changes from upstream 3.5.2, beautifying some JS files
-
- -- Vasily <just.one.man@yandex.ru> Mon, 22 Oct 2018 03:45:13 +0400
-
-emby-server (3.4.1.18-unlocked) unstable; urgency=medium
-
- * Hard fork of Emby 3.4.1.18 including premium unlock
-
- -- Joshua Boniface <joshua@boniface.me> Thu, 9 Aug 2018 00:33:19 -0400
-
diff --git a/debian/conf/jellyfin b/debian/conf/jellyfin
index fb00e7f65..861865aae 100644
--- a/debian/conf/jellyfin
+++ b/debian/conf/jellyfin
@@ -15,8 +15,10 @@
# General options
#
-# Data directory
-JELLYFIN_DATA="/var/lib/jellyfin"
+# Program directories
+JELLYFIN_DATA_DIRECTORY="/var/lib/jellyfin"
+JELLYFIN_CONFIG_DIRECTORY="/etc/jellyfin"
+JELLYFIN_LOG_DIRECTORY="/var/log/jellyfin"
# Restart script for in-app server control
JELLYFIN_RESTART_SCRIPT="/usr/lib/jellyfin/restart.sh"
# Additional options for the binary
@@ -29,4 +31,4 @@ JELLYFIN_ADD_OPTS=""
# Application username
JELLYFIN_USER="jellyfin"
# Full application command
-JELLYFIN_ARGS="-programdata $JELLYFIN_DATA -restartpath $JELLYFIN_RESTART_SCRIPT $JELLYFIN_ADD_OPTS"
+JELLYFIN_ARGS="-programdata $JELLYFIN_DATA_DIRECTORY -configdir $JELLYFIN_CONFIG_DIRECTORY -logdir $JELLYFIN_LOG_DIRECTORY -restartpath $JELLYFIN_RESTART_SCRIPT $JELLYFIN_ADD_OPTS"
diff --git a/debian/conf/logging.json b/debian/conf/logging.json
new file mode 100644
index 000000000..5d98484cd
--- /dev/null
+++ b/debian/conf/logging.json
@@ -0,0 +1,29 @@
+{
+ "Serilog": {
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ { "Name": "Console",
+ "Args": {
+ "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}"
+ }
+ },
+ {
+ "Name": "Async",
+ "Args": {
+ "configure": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "%JELLYFIN_LOG_DIR%//jellyfin.log",
+ "fileSizeLimitBytes": 10485700,
+ "rollOnFileSizeLimit": true,
+ "retainedFileCountLimit": 10,
+ "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/debian/control b/debian/control
index 13c62c806..74bebeaf1 100644
--- a/debian/control
+++ b/debian/control
@@ -9,6 +9,9 @@ Build-Depends: debhelper (>= 9),
libfontconfig1-dev,
libfreetype6-dev
Standards-Version: 3.9.4
+Homepage: https://jellyfin.media/
+Vcs-Git: https://github.org/jellyfin/jellyfin.git
+Vcs-Browser: https://github.org/jellyfin/jellyfin
Package: jellyfin
Replaces: mediabrowser, emby, emby-server-beta, jellyfin-dev, emby-server
diff --git a/debian/install b/debian/install
index bc26f9f09..adaff7b26 100644
--- a/debian/install
+++ b/debian/install
@@ -1,5 +1,6 @@
usr/lib/jellyfin usr/lib/
debian/conf/jellyfin etc/default/
+debian/conf/logging.json etc/jellyfin/
debian/conf/jellyfin.service.conf etc/systemd/system/jellyfin.service.d/
debian/bin/jellyfin-sudoers etc/sudoers.d/
debian/bin/restart.sh usr/lib/jellyfin/
diff --git a/debian/jellyfin.service b/debian/jellyfin.service
index 4c3739909..c17422029 100644
--- a/debian/jellyfin.service
+++ b/debian/jellyfin.service
@@ -6,7 +6,7 @@ After = network.target
Type = simple
EnvironmentFile = /etc/default/jellyfin
User = jellyfin
-ExecStart = /usr/bin/jellyfin -programdata ${JELLYFIN_DATA} -restartpath ${JELLYFIN_RESTART_SCRIPT} ${JELLYFIN_ADD_OPTS}
+ExecStart = /usr/bin/jellyfin -programdata ${JELLYFIN_DATA_DIRECTORY} -configdir ${JELLYFIN_CONFIG_DIRECTORY} -logdir ${JELLYFIN_LOG_DIRECTORY} -restartpath ${JELLYFIN_RESTART_SCRIPT} ${JELLYFIN_ADD_OPTS}
Restart = on-failure
TimeoutSec = 15
diff --git a/debian/postinst b/debian/postinst
index 502bba342..3690d20ba 100644
--- a/debian/postinst
+++ b/debian/postinst
@@ -2,7 +2,6 @@
set -e
NAME=jellyfin
-CONF_FILE=/etc/${NAME}.conf
DEFAULT_FILE=/etc/default/${NAME}
# Source Jellyfin default configuration
@@ -10,13 +9,10 @@ if [[ -f $DEFAULT_FILE ]]; then
. $DEFAULT_FILE
fi
-# Source Jellyfin user configuration overrides
-if [[ -f $CONF_FILE ]]; then
- . $CONF_FILE
-fi
-
-# Data directory where Jellyfin database, cache and logs are stored
-PROGRAMDATA=${JELLYFIN_DATA-/var/lib/$NAME}
+# Data directories for program data (cache, db), configs, and logs
+PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME}
+CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME}
+LOGDATA=${JELLYFIN_LOG_DIRECTORY-/var/log/$NAME}
case "$1" in
configure)
@@ -29,13 +25,24 @@ case "$1" in
adduser --system --ingroup jellyfin --shell /bin/false jellyfin --no-create-home --home ${PROGRAMDATA} \
--gecos "Jellyfin default user" > /dev/null 2>&1
fi
- # ensure $PROGRAMDATA has appropriate permissions
+ # ensure $PROGRAMDATA exists
if [[ ! -d $PROGRAMDATA ]]; then
mkdir $PROGRAMDATA
- chown -R jellyfin:jellyfin $PROGRAMDATA
fi
+ # ensure $CONFIGDATA exists
+ if [[ ! -d $CONFIGDATA ]]; then
+ mkdir $CONFIGDATA
+ fi
+ # ensure $LOGDATA exists
+ if [[ ! -d $LOGDATA ]]; then
+ mkdir $LOGDATA
+ fi
+ # Ensure permissions are correct on all config directories
+ chown -R jellyfin:jellyfin $PROGRAMDATA
+ chown -R jellyfin:jellyfin $CONFIGDATA
+ chown -R jellyfin:jellyfin $LOGDATA
- chmod +x ${JELLYFIN_DIR}/restart.sh > /dev/null 2>&1 || true
+ chmod +x /usr/lib/jellyfin/restart.sh > /dev/null 2>&1 || true
# Install jellyfin symlink into /usr/bin
ln -sf /usr/lib/jellyfin/bin/jellyfin /usr/bin/jellyfin
diff --git a/debian/postrm b/debian/postrm
index 852841b16..690f5d587 100644
--- a/debian/postrm
+++ b/debian/postrm
@@ -2,7 +2,6 @@
set -e
NAME=jellyfin
-CONF_FILE=/etc/${NAME}.conf
DEFAULT_FILE=/etc/default/${NAME}
# Source Jellyfin default configuration
@@ -10,13 +9,10 @@ if [[ -f $DEFAULT_FILE ]]; then
. $DEFAULT_FILE
fi
-# Source Jellyfin user configuration overrides
-if [[ -f $CONF_FILE ]]; then
- . $CONF_FILE
-fi
-
-# Data directory where Jellyfin database, cache and logs are stored
-PROGRAMDATA=${JELLYFIN_DATA-/var/lib/$NAME}
+# Data directories for program data (cache, db), configs, and logs
+PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME}
+CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME}
+LOGDATA=${JELLYFIN_DATA_DIRECTORY-/var/log/$NAME}
# In case this system is running systemd, we make systemd reload the unit files
# to pick up changes.
@@ -37,14 +33,29 @@ case "$1" in
deb-systemd-helper unmask jellyfin.service >/dev/null
fi
+ # Remove user and group
userdel jellyfin > /dev/null 2>&1 || true
delgroup --quiet jellyfin > /dev/null 2>&1 || true
+ # Remove config dir
+ if [[ -d $CONFIGDATA ]]; then
+ rm -rf $CONFIGDATA
+ fi
+ # Remove log dir
+ if [[ -d $LOGDATA ]]; then
+ rm -rf $LOGDATA
+ fi
+ # Remove program data dir
if [[ -d $PROGRAMDATA ]]; then
rm -rf $PROGRAMDATA
fi
+ # Remove binary symlink
[[ -f /usr/bin/jellyfin ]] && rm /usr/bin/jellyfin
+ # Remove sudoers config
[[ -f /etc/sudoers.d/jellyfin-sudoers ]] && rm /etc/sudoers.d/jellyfin-sudoers
- [[ -d /var/lib/jellyfin ]] && rm -rf /var/lib/jellyfin
+ # Remove anything at the default locations; catches situations where the user moved the defaults
+ [[ -e /etc/jellyfin ]] && rm -rf /etc/jellyfin
+ [[ -e /var/log/jellyfin ]] && rm -rf /var/log/jellyfin
+ [[ -e /var/lib/jellyfin ]] && rm -rf /var/lib/jellyfin
;;
remove)
if [[ -x "/usr/bin/deb-systemd-helper" ]]; then
diff --git a/debian/preinst b/debian/preinst
index 2ce29a0cf..0063e0e63 100644
--- a/debian/preinst
+++ b/debian/preinst
@@ -2,7 +2,6 @@
set -e
NAME=jellyfin
-CONF_FILE=/etc/${NAME}.conf
DEFAULT_FILE=/etc/default/${NAME}
# Source Jellyfin default configuration
@@ -10,13 +9,10 @@ if [[ -f $DEFAULT_FILE ]]; then
. $DEFAULT_FILE
fi
-# Source Jellyfin user configuration overrides
-if [[ -f $CONF_FILE ]]; then
- . $CONF_FILE
-fi
-
-# Data directory where Jellyfin database, cache and logs are stored
-PROGRAMDATA=${JELLYFIN_DATA-/var/lib/$NAME}
+# Data directories for program data (cache, db), configs, and logs
+PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME}
+CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME}
+LOGDATA=${JELLYFIN_DATA_DIRECTORY-/var/log/$NAME}
# In case this system is running systemd, we make systemd reload the unit files
# to pick up changes.
@@ -57,6 +53,14 @@ case "$1" in
# Clean up old Emby cruft that can break the user's system
[[ -f /etc/sudoers.d/emby ]] && rm -f /etc/sudoers.d/emby
+ # If we have existing config or log dirs in /var/lib/jellyfin, move them into the right place
+ if [[ -d $PROGRAMDATA/config ]]; then
+ mv $PROGRAMDATA/config $CONFIGDATA
+ fi
+ if [[ -d $PROGRAMDATA/logs ]]; then
+ mv $PROGRAMDATA/logs $LOGDATA
+ fi
+
;;
abort-upgrade)
;;
diff --git a/debian/prerm b/debian/prerm
index 3cdffed79..4770c03c4 100644
--- a/debian/prerm
+++ b/debian/prerm
@@ -2,7 +2,6 @@
set -e
NAME=jellyfin
-CONF_FILE=/etc/${NAME}.conf
DEFAULT_FILE=/etc/default/${NAME}
# Source Jellyfin default configuration
@@ -10,13 +9,10 @@ if [[ -f $DEFAULT_FILE ]]; then
. $DEFAULT_FILE
fi
-# Source Jellyfin user configuration overrides
-if [[ -f $CONF_FILE ]]; then
- . $CONF_FILE
-fi
-
-# Data directory where Jellyfin database, cache and logs are stored
-PROGRAMDATA=${JELLYFIN_DATA-/var/lib/$NAME}
+# Data directories for program data (cache, db), configs, and logs
+PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME}
+CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME}
+LOGDATA=${JELLYFIN_DATA_DIRECTORY-/var/log/$NAME}
case "$1" in
remove|upgrade|deconfigure)
diff --git a/debian/source/options b/debian/source/options
new file mode 100644
index 000000000..45bef4764
--- /dev/null
+++ b/debian/source/options
@@ -0,0 +1 @@
+tar-ignore = ".git*"