Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit844df27

Browse files
committed
download and validator to functions
1 parent4eac98b commit844df27

File tree

3 files changed

+66
-72
lines changed

3 files changed

+66
-72
lines changed

‎Coder Desktop/VPN/Manager.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import VPNLib
44

55
actorManager{
66
letptp:PacketTunnelProvider
7-
letdownloader:Downloader
87

98
vartunnelHandle:TunnelHandle?
109
varspeaker:Speaker<Vpn_ManagerMessage,Vpn_TunnelMessage>?
@@ -16,6 +15,5 @@ actor Manager {
1615

1716
init(with:PacketTunnelProvider){
1817
ptp= with
19-
downloader=Downloader()
2018
}
2119
}

‎Coder Desktop/VPNLib/Downloader.swiftrenamed to‎Coder Desktop/VPNLib/Download.swift

Lines changed: 59 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
import CryptoKit
22
import Foundation
33

4-
publicprotocolValidator:Sendable{
5-
func validate(path:URL)asyncthrows
6-
}
7-
84
publicenumValidationError:Error{
95
case fileNotFound
106
case unableToCreateStaticCode
@@ -37,114 +33,114 @@ public enum ValidationError: Error {
3733
}
3834
}
3935

40-
publicstructSignatureValidator:Validator{
41-
privateletexpectedName="CoderVPN"
42-
privateletexpectedIdentifier="com.coder.Coder-Desktop.VPN.dylib"
43-
privateletexpectedTeamIdentifier="4399GN35BJ"
44-
privateletminDylibVersion="2.18.1"
36+
publicclassSignatureValidator{
37+
privatestaticletexpectedName="CoderVPN"
38+
privatestaticletexpectedIdentifier="com.coder.Coder-Desktop.VPN.dylib"
39+
privatestaticletexpectedTeamIdentifier="4399GN35BJ"
40+
privatestaticletminDylibVersion="2.18.1"
4541

46-
privateletinfoIdentifierKey="CFBundleIdentifier"
47-
privateletinfoNameKey="CFBundleName"
48-
privateletinfoShortVersionKey="CFBundleShortVersionString"
42+
privatestaticletinfoIdentifierKey="CFBundleIdentifier"
43+
privatestaticletinfoNameKey="CFBundleName"
44+
privatestaticletinfoShortVersionKey="CFBundleShortVersionString"
4945

50-
privateletsignInfoFlags:SecCSFlags=.init(rawValue: kSecCSSigningInformation)
46+
privatestaticletsignInfoFlags:SecCSFlags=.init(rawValue: kSecCSSigningInformation)
5147

52-
publicinit(){}
53-
54-
publicfunc validate(path:URL)throws{
48+
publicstaticfunc validate(path:URL)throws(ValidationError){
5549
guardFileManager.default.fileExists(atPath: path.path)else{
56-
throwValidationError.fileNotFound
50+
throw.fileNotFound
5751
}
5852

5953
varstaticCode:SecStaticCode?
6054
letstatus=SecStaticCodeCreateWithPath(pathasCFURL,SecCSFlags(),&staticCode)
6155
guard status== errSecSuccess,let code= staticCodeelse{
62-
throwValidationError.unableToCreateStaticCode
56+
throw.unableToCreateStaticCode
6357
}
6458

6559
letvalidateStatus=SecStaticCodeCheckValidity(code,SecCSFlags(),nil)
6660
guard validateStatus== errSecSuccesselse{
67-
throwValidationError.invalidSignature
61+
throw.invalidSignature
6862
}
6963

7064
varinformation:CFDictionary?
7165
letinfoStatus=SecCodeCopySigningInformation(code, signInfoFlags,&information)
7266
guard infoStatus== errSecSuccess,let info= informationas?[String:Any]else{
73-
throwValidationError.unableToRetrieveInfo
67+
throw.unableToRetrieveInfo
7468
}
7569

7670
guardlet identifier=info[kSecCodeInfoIdentifierasString]as?String,
7771
identifier== expectedIdentifier
7872
else{
79-
throwValidationError.invalidIdentifier(identifier:info[kSecCodeInfoIdentifierasString]as?String)
73+
throw.invalidIdentifier(identifier:info[kSecCodeInfoIdentifierasString]as?String)
8074
}
8175

8276
guardlet teamIdentifier=info[kSecCodeInfoTeamIdentifierasString]as?String,
8377
teamIdentifier== expectedTeamIdentifier
8478
else{
85-
throwValidationError.invalidTeamIdentifier(
79+
throw.invalidTeamIdentifier(
8680
identifier:info[kSecCodeInfoTeamIdentifierasString]as?String
8781
)
8882
}
8983

9084
guardlet infoPlist=info[kSecCodeInfoPListasString]as?[String:AnyObject]else{
91-
throwValidationError.missingInfoPList
85+
throw.missingInfoPList
9286
}
9387

9488
guardlet plistIdent=infoPlist[infoIdentifierKey]as?String, plistIdent== expectedIdentifierelse{
95-
throwValidationError.invalidIdentifier(identifier:infoPlist[infoIdentifierKey]as?String)
89+
throw.invalidIdentifier(identifier:infoPlist[infoIdentifierKey]as?String)
9690
}
9791

9892
guardlet plistName=infoPlist[infoNameKey]as?String, plistName== expectedNameelse{
99-
throwValidationError.invalidIdentifier(identifier:infoPlist[infoNameKey]as?String)
93+
throw.invalidIdentifier(identifier:infoPlist[infoNameKey]as?String)
10094
}
10195

10296
guardlet dylibVersion=infoPlist[infoShortVersionKey]as?String,
10397
minDylibVersion.compare(dylibVersion, options:.numeric)!=.orderedDescending
10498
else{
105-
throwValidationError.invalidVersion(version:infoPlist[infoShortVersionKey]as?String)
99+
throw.invalidVersion(version:infoPlist[infoShortVersionKey]as?String)
106100
}
107101
}
108102
}
109103

110-
publicstructDownloader:Sendable{
111-
letvalidator:Validator
112-
publicinit(validator:Validator=SignatureValidator()){
113-
self.validator= validator
114-
}
115-
116-
publicfunc download(src:URL, dest:URL)asyncthrows{
117-
varreq=URLRequest(url: src)
118-
ifFileManager.default.fileExists(atPath: dest.path){
119-
iflet existingFileData=try?Data(contentsOf: dest, options:.mappedIfSafe){
120-
req.setValue(etag(data: existingFileData), forHTTPHeaderField:"If-None-Match")
121-
}
104+
publicfunc download(src:URL, dest:URL)asyncthrows(DownloadError){
105+
varreq=URLRequest(url: src)
106+
ifFileManager.default.fileExists(atPath: dest.path){
107+
iflet existingFileData=try?Data(contentsOf: dest, options:.mappedIfSafe){
108+
req.setValue(etag(data: existingFileData), forHTTPHeaderField:"If-None-Match")
122109
}
123-
// TODO: Add Content-Length headers to coderd, add download progress delegate
124-
let(tempURL, response)=tryawaitURLSession.shared.download(for: req)
125-
defer{
126-
ifFileManager.default.fileExists(atPath: tempURL.path){
127-
do{tryFileManager.default.removeItem(at: tempURL)}catch{}
128-
}
110+
}
111+
// TODO: Add Content-Length headers to coderd, add download progress delegate
112+
lettempURL:URL
113+
letresponse:URLResponse
114+
do{
115+
(tempURL, response)=tryawaitURLSession.shared.download(for: req)
116+
}catch{
117+
throw.networkError(error)
118+
}
119+
defer{
120+
ifFileManager.default.fileExists(atPath: tempURL.path){
121+
try?FileManager.default.removeItem(at: tempURL)
129122
}
123+
}
130124

131-
guardlet httpResponse= responseas?HTTPURLResponseelse{
132-
throwDownloadError.invalidResponse
133-
}
134-
guard httpResponse.statusCode!=304else{
135-
// We already have the latest dylib downloaded on disk
136-
return
137-
}
125+
guardlet httpResponse= responseas?HTTPURLResponseelse{
126+
throw.invalidResponse
127+
}
128+
guard httpResponse.statusCode!=304else{
129+
// We already have the latest dylib downloaded on disk
130+
return
131+
}
138132

139-
guard httpResponse.statusCode==200else{
140-
throwDownloadError.unexpectedStatusCode(httpResponse.statusCode)
141-
}
133+
guard httpResponse.statusCode==200else{
134+
throw.unexpectedStatusCode(httpResponse.statusCode)
135+
}
142136

137+
do{
143138
ifFileManager.default.fileExists(atPath: dest.path){
144139
tryFileManager.default.removeItem(at: dest)
145140
}
146141
tryFileManager.default.moveItem(at: tempURL, to: dest)
147-
tryawait validator.validate(path: dest)
142+
}catch{
143+
throw.fileOpError(error)
148144
}
149145
}
150146

@@ -154,14 +150,20 @@ func etag(data: Data) -> String {
154150
return"\"\(etag)\""
155151
}
156152

157-
enumDownloadError:Error{
153+
publicenumDownloadError:Error{
158154
case unexpectedStatusCode(Int)
159155
case invalidResponse
156+
case networkError(anyError)
157+
case fileOpError(anyError)
160158

161159
varlocalizedDescription:String{
162160
switchself{
163161
caselet.unexpectedStatusCode(code):
164-
return"Unexpected status code:\(code)"
162+
return"Unexpected HTTP status code:\(code)"
163+
caselet.networkError(error):
164+
return"Network error:\(error.localizedDescription)"
165+
caselet.fileOpError(error):
166+
return"File operation error:\(error.localizedDescription)"
165167
case.invalidResponse:
166168
return"Received non-HTTP response"
167169
}

‎Coder Desktop/VPNLibTests/DownloaderTests.swiftrenamed to‎Coder Desktop/VPNLibTests/DownloadTests.swift

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,8 @@ import Mocker
33
import Testing
44
@testableimport VPNLib
55

6-
structNoopValidator:Validator{
7-
func validate(path _:URL)asyncthrows{}
8-
}
9-
10-
@Suite
11-
structDownloaderTests{
12-
letdownloader=Downloader(validator:NoopValidator())
13-
6+
@Suite(.timeLimit(.minutes(1)))
7+
structDownloadTests{
148
@Test
159
func downloadFile()asyncthrows{
1610
letdestinationURL=FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
@@ -19,7 +13,7 @@ struct DownloaderTests {
1913
letfileURL=URL(string:"http://example.com/test1.txt")!
2014
Mock(url: fileURL, contentType:.html, statusCode:200, data:[.get: testData]).register()
2115

22-
tryawaitdownloader.download(src: fileURL, dest: destinationURL)
16+
tryawaitdownload(src: fileURL, dest: destinationURL)
2317

2418
try #require(FileManager.default.fileExists(atPath: destinationURL.path))
2519
defer{try?FileManager.default.removeItem(at: destinationURL)}
@@ -38,7 +32,7 @@ struct DownloaderTests {
3832

3933
Mock(url: fileURL, contentType:.html, statusCode:200, data:[.get: testData]).register()
4034

41-
tryawaitdownloader.download(src: fileURL, dest: destinationURL)
35+
tryawaitdownload(src: fileURL, dest: destinationURL)
4236
try #require(FileManager.default.fileExists(atPath: destinationURL.path))
4337
letdownloadedData=tryData(contentsOf: destinationURL)
4438
#expect(downloadedData== testData)
@@ -50,7 +44,7 @@ struct DownloaderTests {
5044
}
5145
mock.register()
5246

53-
tryawaitdownloader.download(src: fileURL, dest: destinationURL)
47+
tryawaitdownload(src: fileURL, dest: destinationURL)
5448
letunchangedData=tryData(contentsOf: destinationURL)
5549
#expect(unchangedData== testData)
5650
#expect(etagIncluded)
@@ -67,7 +61,7 @@ struct DownloaderTests {
6761

6862
Mock(url: fileURL, contentType:.html, statusCode:200, data:[.get: ogData]).register()
6963

70-
tryawaitdownloader.download(src: fileURL, dest: destinationURL)
64+
tryawaitdownload(src: fileURL, dest: destinationURL)
7165
try #require(FileManager.default.fileExists(atPath: destinationURL.path))
7266
vardownloadedData=tryData(contentsOf: destinationURL)
7367
#expect(downloadedData== ogData)
@@ -79,7 +73,7 @@ struct DownloaderTests {
7973
}
8074
mock.register()
8175

82-
tryawaitdownloader.download(src: fileURL, dest: destinationURL)
76+
tryawaitdownload(src: fileURL, dest: destinationURL)
8377
downloadedData=tryData(contentsOf: destinationURL)
8478
#expect(downloadedData== newData)
8579
#expect(etagIncluded)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp