Home telegram - transformOutgoingMessageMedia
Post
Cancel

telegram - transformOutgoingMessageMedia

1
public typealias TransformOutgoingMessageMedia = (_ postbox: Postbox, _ network: Network, _ media: AnyMediaReference, _ userInteractive: Bool) -> Signal<AnyMediaReference?, NoError>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
public func transformOutgoingMessageMedia(postbox: Postbox, network: Network, media: AnyMediaReference, opportunistic: Bool) -> Signal<AnyMediaReference?, NoError> {
    switch media.media {
      // file
        case let file as TelegramMediaFile:
            let signal = Signal<MediaResourceData, NoError> { subscriber in
                let fetch = fetchedMediaResource(mediaBox: postbox.mediaBox, reference: media.resourceReference(file.resource)).start()
                let data = postbox.mediaBox.resourceData(file.resource, option: .complete(waitUntilFetchStatus: true)).start(next: { next in
                    subscriber.putNext(next)
                    if next.complete {
                        subscriber.putCompletion()
                    }
                })
                
                return ActionDisposable {
                    fetch.dispose()
                    data.dispose()
                }
            }
            
            let result: Signal<MediaResourceData, NoError>
            if opportunistic {
                result = signal |> take(1)
            } else {
                result = signal
            }
            
            return result
            |> mapToSignal { data -> Signal<AnyMediaReference?, NoError> in
                if data.complete {
                    if file.mimeType.hasPrefix("image/") {
                        return Signal { subscriber in
                            if let fullSizeData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) {
                                let options = NSMutableDictionary()
                                options[kCGImageSourceShouldCache as NSString] = false as NSNumber
                                if let imageSource = CGImageSourceCreateWithData(fullSizeData as CFData, nil), let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, options as CFDictionary) {
                                    let imageOrientation = imageOrientationFromSource(imageSource)
                                    
                                    let image = UIImage(cgImage: cgImage, scale: 1.0, orientation: imageOrientation)
                            
                                    if let scaledImage = generateImage(image.size.fitted(CGSize(width: 320.0, height: 320.0)), contextGenerator: { size, context in
                                        context.setBlendMode(.copy)
                                        drawImage(context: context, image: image.cgImage!, orientation: image.imageOrientation, in: CGRect(origin: CGPoint(), size: size))
                                    }, scale: 1.0), let thumbnailData = scaledImage.jpegData(compressionQuality: 0.6) {
                                        /*if #available(iOSApplicationExtension 11.0, iOS 11.0, *) {
                                            #if DEBUG
                                            if true, let heicData = compressImage(scaledImage, quality: 0.7) {
                                                print("data \(thumbnailData.count), heicData \(heicData.count)")
                                            }
                                            #endif
                                        }*/
                                        let imageDimensions = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
                                        
                                        let thumbnailResource = LocalFileMediaResource(fileId: arc4random64())
                                        postbox.mediaBox.storeResourceData(thumbnailResource.id, data: thumbnailData)
                                        
                                        let scaledImageSize = CGSize(width: scaledImage.size.width * scaledImage.scale, height: scaledImage.size.height * scaledImage.scale)
                                        
                                        var attributes = file.attributes
                                        loop: for i in 0 ..< attributes.count {
                                            switch attributes[i] {
                                                case .ImageSize:
                                                    attributes.remove(at: i)
                                                    break loop
                                                default:
                                                    break
                                            }
                                        }
                                        attributes.append(.ImageSize(size: imageDimensions))
                                        let updatedFile = file.withUpdatedSize(data.size).withUpdatedPreviewRepresentations([TelegramMediaImageRepresentation(dimensions: scaledImageSize, resource: thumbnailResource)]).withUpdatedAttributes(attributes)
                                        subscriber.putNext(.standalone(media: updatedFile))
                                        subscriber.putCompletion()
                                    } else {
                                        let updatedFile = file.withUpdatedSize(data.size)
                                        subscriber.putNext(.standalone(media: updatedFile))
                                        subscriber.putCompletion()
                                    }
                                } else {
                                    let updatedFile = file.withUpdatedSize(data.size)
                                    subscriber.putNext(.standalone(media: updatedFile))
                                    subscriber.putCompletion()
                                }
                            } else {
                                let updatedFile = file.withUpdatedSize(data.size)
                                subscriber.putNext(.standalone(media: updatedFile))
                                subscriber.putCompletion()
                            }
                            
                            return EmptyDisposable
                        } |> runOn(opportunistic ? Queue.mainQueue() : Queue.concurrentDefaultQueue())
                    } else if file.mimeType.hasPrefix("video/") {// video
                        return Signal { subscriber in
                                       // generate first frame
                            if let scaledImage = generateVideoFirstFrame(data.path, maxDimensions: CGSize(width: 320.0, height: 320.0)), let thumbnailData = scaledImage.jpegData(compressionQuality: 0.6) {
                                let thumbnailResource = LocalFileMediaResource(fileId: arc4random64())
                                postbox.mediaBox.storeResourceData(thumbnailResource.id, data: thumbnailData)
                            
                                let scaledImageSize = CGSize(width: scaledImage.size.width * scaledImage.scale, height: scaledImage.size.height * scaledImage.scale)
                            
                                let updatedFile = file.withUpdatedSize(data.size).withUpdatedPreviewRepresentations([TelegramMediaImageRepresentation(dimensions: scaledImageSize, resource: thumbnailResource)])
                                subscriber.putNext(.standalone(media: updatedFile))
                                subscriber.putCompletion()
                            } else {
                                let updatedFile = file.withUpdatedSize(data.size)
                                subscriber.putNext(.standalone(media: updatedFile))
                                subscriber.putCompletion()
                            }
                            
                            return EmptyDisposable
                        } |> runOn(opportunistic ? Queue.mainQueue() : Queue.concurrentDefaultQueue())
                    } else {
                        let updatedFile = file.withUpdatedSize(data.size)
                        return .single(.standalone(media: updatedFile))
                    }
                } else if opportunistic {
                    return .single(nil)
                } else {
                    return .complete()
                }
            }
      // image
        case let image as TelegramMediaImage:
            if let representation = largestImageRepresentation(image.representations) {
                let signal = Signal<MediaResourceData, NoError> { subscriber in
                    let fetch = fetchedMediaResource(mediaBox: postbox.mediaBox, reference: media.resourceReference(representation.resource)).start()
                    let data = postbox.mediaBox.resourceData(representation.resource, option: .complete(waitUntilFetchStatus: true)).start(next: { next in
                        subscriber.putNext(next)
                        if next.complete {
                            subscriber.putCompletion()
                        }
                    })
                    
                    return ActionDisposable {
                        fetch.dispose()
                        data.dispose()
                    }
                }
                
                let result: Signal<MediaResourceData, NoError>
                if opportunistic {
                    result = signal
                    |> take(1)
                } else {
                    result = signal
                }
                
                return result
                |> mapToSignal { data -> Signal<AnyMediaReference?, NoError> in
                    if data.complete {
                        if let smallest = smallestImageRepresentation(image.representations), smallest.dimensions.width > 100.0 || smallest.dimensions.height > 100.0 {
                            let smallestSize = smallest.dimensions.fitted(CGSize(width: 320.0, height: 320.0))
                            if let fullImage = UIImage(contentsOfFile: data.path), let smallestImage = generateScaledImage(image: fullImage, size: smallestSize, scale: 1.0), let smallestData = compressImageToJPEG(smallestImage, quality: 0.7) {
                                var representations = image.representations
                                
                                let thumbnailResource = LocalFileMediaResource(fileId: arc4random64())
                                postbox.mediaBox.storeResourceData(thumbnailResource.id, data: smallestData)
                                representations.append(TelegramMediaImageRepresentation(dimensions: smallestSize, resource: thumbnailResource))
                                let updatedImage = TelegramMediaImage(imageId: image.imageId, representations: representations, immediateThumbnailData: image.immediateThumbnailData, reference: image.reference, partialReference: image.partialReference)
                                return .single(.standalone(media: updatedImage))
                            }
                        }
                        
                        return .single(nil)
                    } else if opportunistic {
                        return .single(nil)
                    } else {
                        return .complete()
                    }
                }
            } else {
                return .single(nil)
            }
        default:
            return .single(nil)
    }
}
This post is licensed under CC BY 4.0 by the author.