8
8
9
9
import Foundation
10
10
import ReactiveSwift
11
+ import Swime
11
12
12
13
class GopherPage {
13
14
var request : GopherRequest ?
@@ -29,23 +30,32 @@ class GopherPage {
29
30
}
30
31
31
32
var contentHtml : String
33
+ var contentType : String
32
34
33
35
if ( self . status. value == GopherStatus . Failed) {
34
36
print ( " Showing error... " )
35
37
contentHtml = " Could not load \( self . request!. url) "
38
+ contentType = " error "
39
+ }
40
+ else if ( self . response? . isBinary) ! {
41
+ print ( " Showing binary... " )
42
+ contentHtml = parseBinary ( )
43
+ contentType = " image "
36
44
}
37
45
else if ( self . response? . isDirectory) ! {
38
46
print ( " Showing directory... " )
39
47
contentHtml = parseDirectory ( ) . map ( {
40
48
$0. html
41
49
} ) . joined ( )
50
+ contentType = " directory "
42
51
}
43
52
else {
44
53
print ( " Showing file... " )
45
- contentHtml = parseRaw ( )
54
+ contentHtml = parsePlain ( )
55
+ contentType = " text "
46
56
}
47
57
48
- return " <html><head><style> " + styles + " </style></head><body> " + contentHtml + " </body></html> "
58
+ return " <html><head><style> " + styles + " </style></head><body class= \" type- " + contentType + " \" > " + contentHtml + " </body></html> "
49
59
}
50
60
51
61
let lineSeparator = String ( bytes: [ 13 , 10 ] , encoding: String . Encoding. ascii) !
@@ -74,8 +84,25 @@ class GopherPage {
74
84
}
75
85
}
76
86
77
- private func parseRaw( ) -> String {
78
- guard let body = self . response? . body else {
87
+ private func parseBinary( ) -> String {
88
+ guard let data = self . response? . data else {
89
+ return " "
90
+ }
91
+ let mimeType = Swime . mimeType ( data: data)
92
+ let encodedData = data. base64EncodedString ( )
93
+ switch mimeType? . type {
94
+ case . gif? , . jpg? , . png? , . webp? :
95
+ guard let mime = mimeType? . mime else {
96
+ return " "
97
+ }
98
+ return " <img src= \" data: " + mime + " ;base64, " + encodedData + " \" > "
99
+ default :
100
+ return " "
101
+ }
102
+ }
103
+
104
+ private func parsePlain( ) -> String {
105
+ guard let body = self . response? . text else {
79
106
return " "
80
107
}
81
108
@@ -87,7 +114,7 @@ class GopherPage {
87
114
}
88
115
89
116
private func parseDirectory( ) -> [ GopherResponsePart ] {
90
- guard let parts = self . response? . body . components ( separatedBy: lineSeparator) else {
117
+ guard let parts = self . response? . text ? . components ( separatedBy: lineSeparator) else {
91
118
return [ ]
92
119
}
93
120
0 commit comments