Projet

Général

Profil

Paste
Statistiques
| Branche: | Révision:

root / src / app / home / home.component.ts @ cda781e8

Historique | Voir | Annoter | Télécharger (12 ko)

1
import { Component, OnInit } from "@angular/core";
2
import { takePicture, requestCameraPermissions } from 'nativescript-camera';
3
import { PhotoEditor, PhotoEditorControl } from "nativescript-photo-editor";
4
import { ImageAsset } from 'tns-core-modules/image-asset';
5
import { RadSideDrawer } from "nativescript-ui-sidedrawer";
6
import { knownFolders, Folder, File, path } from "tns-core-modules/file-system";
7
import { ImageSource, fromFile, fromResource, fromBase64, fromAsset } from "tns-core-modules/image-source";
8
import { Image } from "tns-core-modules/ui/image";
9
import { EventData } from "tns-core-modules/data/observable";
10
import { Button } from "tns-core-modules/ui/button";
11
import { getViewById } from "tns-core-modules/ui/core/view";
12
import { TextField } from "tns-core-modules/ui/text-field";
13
import * as appversion from "nativescript-appversion";
14
import { isAndroid, isIOS, device, screen } from "tns-core-modules/platform";
15
import { getString, setString, hasKey, remove, clear } from "tns-core-modules/application-settings";
16

    
17
import * as dialogs from "tns-core-modules/ui/dialogs";
18
import * as app from "tns-core-modules/application";
19
import * as imagepicker from "nativescript-imagepicker";
20

    
21
declare var NSString: any;
22
declare var NSUTF8StringEncoding: any;
23
declare var java: any;
24
declare var android: any;
25
@Component({
26
    selector: "Home",
27
    templateUrl: "./home.component.html"
28
})
29
export class HomeComponent implements OnInit {
30
    public cameraImage: ImageAsset;
31
    public pseudo: string;
32
    public email: string;
33
    public label: string;
34
    public album: string;
35
    public albumPass: string;
36
    private photoEditor;
37
    private appVersion;
38
    public serverName: string;
39
    public serverURI: string;
40
    public hasPicture: boolean;
41

    
42

    
43
    constructor() {
44
        // Use the component constructor to inject providers.
45
        appversion.getVersionName().then((v: string) => {
46
            if (isAndroid) {
47
                this.appVersion = "Android/" + v;
48
            }
49
            else if (isIOS) {
50
                this.appVersion = "iOS/" + v;
51
            }
52
            else {
53
                this.appVersion = "Other/" + v;
54
            }
55
            console.log("Your app's version is: " + this.appVersion);
56
        });
57
    }
58

    
59
    ngOnInit(): void {
60
        // Init your component properties here.
61
        this.photoEditor = new PhotoEditor();
62
        this.hasPicture = false;
63
        this.pseudo = getString("pseudo", "");
64
        this.email = getString("email", "");
65
        this.serverName = getString("serverName", "AbulEdu-FR");
66
        this.serverURI = getString("serverURI", "clicalbum.abuledu.net");
67
        this.album = getString("album", "");
68
        this.albumPass = getString("albumPass", "");
69
        this.label = "";
70
    }
71

    
72
    onBlur(args: EventData): void {
73
        let obj = <TextField>args.object;
74
        if (obj.id == "album") {
75
            this.album = obj.text.toLowerCase().replace(/[^a-z0-9]/g, "");
76
        }
77
        if (obj.id == "albumPass") {
78
            this.albumPass = obj.text.toLowerCase().replace(/[^a-z0-9]/g, "");
79
        }
80
    }
81

    
82
    onDrawerButtonTap(): void {
83
        const sideDrawer = <RadSideDrawer>app.getRootView();
84
        sideDrawer.showDrawer();
85
    }
86

    
87
    onGetPictureFromRollTap(args: EventData) {
88
        var that = this;
89
        let context = imagepicker.create({
90
            mode: "single" // use "multiple" for multiple selection
91
        });
92
        context
93
            .authorize()
94
            .then(function () {
95
                return context.present();
96
            })
97
            .then(function (selection) {
98
                selection.forEach(function (selected) {
99
                    let imageSource = new ImageSource();
100
                    imageSource.fromAsset(selected).then((imageSource) => {
101
                        console.log("ORIG IMAGE SIZE FROM ROLL: " + imageSource.height + " x " + imageSource.width);
102
                        console.dir(imageSource);
103
                        // console.log("un ter");
104

    
105
                        that.photoEditor.editPhoto({
106
                            imageSource: imageSource,
107
                            hiddenControls: [
108
                                PhotoEditorControl.Draw,
109
                                PhotoEditorControl.Text,
110
                                PhotoEditorControl.Clear,
111
                            ],
112
                        }).then((newImage: ImageSource) => {
113
                            console.log("NEW IMAGE: ", newImage.height, newImage.width);
114
                            that.imageCropped(newImage);
115
                            // Here you can save newImage, send it to your backend or simply display it in your app
116
                            // that.resultImage.imageSource = newImage;
117
                        }).catch((e) => {
118
                            console.log("erreur ES 1");
119
                            console.error(e);
120
                        });
121
                        console.log("trois");
122
                    });
123

    
124
                });
125
                console.log("Selection des fichiers ", selection);
126
            }).catch(function (e) {
127
                console.log("Error ES: " + e);
128
                // process error
129
            });
130

    
131
    }
132

    
133
    onTakePictureTap(args: EventData) {
134
        const options = {
135
            keepAspectRatio: true,
136
            saveToGallery: false
137
        };
138

    
139
        // let button = args.object as Button;
140
        requestCameraPermissions().then(
141
            () => {
142
                takePicture(options)
143
                    .then((imageAsset: any) => {
144
                        let imageSource = new ImageSource();
145

    
146
                        imageSource.fromAsset(imageAsset).then((imageSource) => {
147
                            console.log("ORIG IMAGE SIZE: " + imageSource.height + " x " + imageSource.width);
148
                            console.dir(imageSource);
149
                            // console.log("un ter");
150

    
151
                            this.photoEditor.editPhoto({
152
                                imageSource: imageSource,
153
                                hiddenControls: [
154
                                    PhotoEditorControl.Draw,
155
                                    PhotoEditorControl.Text,
156
                                    PhotoEditorControl.Clear,
157
                                ],
158
                            }).then((newImage: ImageSource) => {
159
                                console.log("NEW IMAGE: ", newImage.height, newImage.width);
160
                                this.imageCropped(newImage);
161
                                // Here you can save newImage, send it to your backend or simply display it in your app
162
                                // this.resultImage.imageSource = newImage;
163
                            }).catch((e) => {
164
                                console.log("erreur 1");
165
                                console.error(e);
166
                            });
167
                            console.log("trois");
168
                        });
169

    
170
                    }, (error) => {
171
                        console.log("Error: " + error);
172
                    });
173
            },
174
            () => alert('permissions rejected')
175
        );
176
    }
177

    
178
    onResetPictureTap(args) {
179
        // this.cameraImage = "res://icon";
180
    }
181

    
182
    onGotoWebTap() {
183
        if (this.album == "") {
184
            dialogs.alert({
185
                title: "Nom d'album",
186
                message: "Il faut renseigner le nom de l'album que vous voulez consulter ...",
187
                okButtonText: "Ok"
188
            }).then(() => {
189
            });
190
        }
191

    
192
        var utilityModule = require("utils/utils");
193
        utilityModule.openUrl("https://" + this.serverURI + "/" + this.album);
194
    }
195

    
196
    onSendPictureTap(args) {
197
        let labelObj = <TextField>getViewById(app.getRootView(), "label");
198
        this.label = labelObj.text;
199
        let albumObj = <TextField>getViewById(app.getRootView(), "album");
200
        this.album = albumObj.text;
201
        albumObj = <TextField>getViewById(app.getRootView(), "albumPass");
202
        this.albumPass = albumObj.text;
203

    
204
        console.log("on a maintenant ", this.albumPass);
205

    
206

    
207
        if (this.album == "" || this.label == "") {
208
            dialogs.alert({
209
                title: "Informations manquantes",
210
                message: "Il faut renseigner le nom de l'album auquel vous voulez participer et donner un nom à votre photo ...",
211
                okButtonText: "Ok"
212
            }).then(() => {
213
            });
214
        }
215
        else {
216
            setString("album", this.album);
217
            setString("albumPass", this.albumPass);
218
            this.sendPicture(args);
219
        }
220
    }
221

    
222
    sendPicture(args) {
223
        // let button = args.object as Button;
224
        const folderPath: string = knownFolders.documents().path;
225
        const fileName = "fichier_temporaire.jpeg";
226
        const filePath = path.join(folderPath, fileName);
227
        console.log("On voudrait uploader le fichier " + filePath + " dans l'album " + this.album);
228

    
229
        var url = "https://" + this.serverURI + "/u.php";
230

    
231
        // // upload configuration
232
        var bghttp = require("nativescript-background-http");
233
        var session = bghttp.session("image-upload");
234
        var request = {
235
            url: url,
236
            method: "POST",
237
            headers: {
238
                "Content-Type": "application/octet-stream",
239
                "User-Agent": "ClicAlbum " + this.appVersion,
240
            },
241
            description: "Uploading " + fileName
242
        };
243

    
244
        var params = [
245
            { name: "login", value: this.base64Encode(this.pseudo) },
246
            { name: "email", value: this.base64Encode(this.email) },
247
            { name: "label", value: this.base64Encode(this.label) },
248
            { name: "album", value: this.base64Encode(this.album) },
249
            { name: "albumPass", value: this.base64Encode(this.albumPass) },
250
            { name: "version", value: "2" },
251
            { name: "fileToUpload", filename: filePath, mimeType: "image/jpeg" }
252
        ];
253
        var task = session.multipartUpload(params, request);
254

    
255
        task.on("progress", logEvent);
256
        task.on("error", uploadError);
257
        task.on("complete", resetPicture);
258

    
259
        function logEvent(e) {
260
            console.log("UPLOAD STATUS: " + e.eventName);
261
        }
262

    
263
        function uploadError(e) {
264
            dialogs.alert({
265
                title: "Erreur de transfert",
266
                message: "Erreur de transfert, peut-être que cet album est protégé par mot de passe et que celui que vous avez indiqué n'est pas bon ?",
267
                okButtonText: "Ok"
268
            }).then(() => {
269

    
270
            });
271
        }
272

    
273
        function resetPicture() {
274
            console.log("UPLOAD STATUS: terminé");
275
            this.cameraImage = "res://icon";
276
            console.log("UPLOAD STATUS: terminé end");
277
            dialogs.alert({
278
                title: "Téléversement terminé",
279
                message: "Votre document est maintenant sur le serveur",
280
                okButtonText: "Ok"
281
            }).then(() => {
282
                console.log("Dialog closed!");
283
                this.cameraImage = "res://icon";
284
            });
285
        }
286
    }
287

    
288
    imageCropped(image) {
289
        this.cameraImage = image;
290
        console.log("imageCropped ...");
291
        console.log("NEW IMAGE: ", image.height, image.width);
292

    
293
        //     // =========== sauvegarde de l'image
294
        const folderPath: string = knownFolders.documents().path;
295
        const fileName = "fichier_temporaire.jpeg";
296
        const filePath = path.join(folderPath, fileName);
297
        const saved: boolean = image.saveToFile(filePath, "jpeg", 95);
298
        if (saved) {
299
            console.log("Image saved successfully in " + filePath);
300
        }
301
        //     // =========== end sauvegarde de l'image
302
        this.hasPicture = true;
303
    }
304

    
305
    base64Encode(value) {
306
        if (isIOS) {
307
            let text = NSString.stringWithString(value);
308
            let data = text.dataUsingEncoding(NSUTF8StringEncoding);
309
            return data.base64EncodedStringWithOptions(0);
310
        } else {
311
            let text = new java.lang.String(value);
312
            let data = text.getBytes("UTF-8");
313
            return android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
314
        }
315
    }
316

    
317
}
Redmine Appliance - Powered by TurnKey Linux