Projet

Général

Profil

Paste
Statistiques
| Branche: | Révision:

root / src / app / home / home.component.ts @ 25220fd6

Historique | Voir | Annoter | Télécharger (15,6 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 { getViewById } from "tns-core-modules/ui/core/view";
11
import { TextField } from "tns-core-modules/ui/text-field";
12
import { isAndroid, isIOS, device, screen } from "tns-core-modules/platform";
13
import { ActivityIndicator } from "tns-core-modules/ui/activity-indicator";
14
import { getString, setString, hasKey, remove, clear } from "tns-core-modules/application-settings";
15
import { Button } from "tns-core-modules/ui/button";
16

    
17
import * as bghttp from "nativescript-background-http";
18
import * as appversion from "nativescript-appversion";
19
import * as dialogs from "tns-core-modules/ui/dialogs";
20
import * as app from "tns-core-modules/application";
21
import * as imagepicker from "nativescript-imagepicker";
22

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

    
46

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

    
63
    ngOnInit(): void {
64
        // Init your component properties here.
65
        this.photoEditor = new PhotoEditor();
66
        this.hasPicture = false;
67
        this.pseudo = getString("pseudo", "");
68
        this.email = getString("email", "");
69
        this.serverName = getString("serverName", "AbulEdu-FR");
70
        this.serverURI = getString("serverURI", "clicalbum.abuledu.net");
71
        this.album = getString("album", "");
72
        this.albumPass = getString("albumPass", "");
73
        this.label = "";
74
        this.legende = "";
75
        this.isBusy = false;
76
        this.enableButtons("btnSendPicture", false)
77
    }
78

    
79
    enableButtons(btnName, onOff) {
80
        let b = <Button>getViewById(app.getRootView(), btnName);
81
        if (b) {
82
            b.isEnabled = onOff;
83
        }
84
    }
85

    
86

    
87
    onBlur(args: EventData): void {
88
        let obj = <TextField>args.object;
89
        if (obj.id == "album") {
90
            this.album = obj.text.toLowerCase().replace(/[^a-z0-9]/g, "");
91
        }
92
        if (obj.id == "albumPass") {
93
            this.albumPass = obj.text.toLowerCase().replace(/[^a-z0-9]/g, "");
94
        }
95
    }
96

    
97
    onDrawerButtonTap(): void {
98
        const sideDrawer = <RadSideDrawer>app.getRootView();
99
        sideDrawer.showDrawer();
100
    }
101

    
102
    onGetPictureFromRollTap(args: EventData) {
103
        var that = this;
104
        let context = imagepicker.create({
105
            mode: "single" // use "multiple" for multiple selection
106
        });
107
        context
108
            .authorize()
109
            .then(function () {
110
                return context.present();
111
            })
112
            .then(function (selection) {
113
                selection.forEach(function (selected) {
114
                    let imageSource = new ImageSource();
115
                    imageSource.fromAsset(selected).then((imageSource) => {
116
                        console.log("ORIG IMAGE SIZE FROM ROLL: " + imageSource.height + " x " + imageSource.width);
117
                        console.dir(imageSource);
118
                        // console.log("un ter");
119

    
120
                        that.photoEditor.editPhoto({
121
                            imageSource: imageSource,
122
                            hiddenControls: [
123
                                PhotoEditorControl.Draw,
124
                                PhotoEditorControl.Text,
125
                                PhotoEditorControl.Clear,
126
                            ],
127
                        }).then((newImage: ImageSource) => {
128
                            console.log("NEW IMAGE: ", newImage.height, newImage.width);
129
                            that.imageCropped(newImage);
130
                            // Here you can save newImage, send it to your backend or simply display it in your app
131
                            // that.resultImage.imageSource = newImage;
132
                        }).catch((e) => {
133
                            console.log("erreur ES 1");
134
                            console.error(e);
135
                        });
136
                        console.log("trois");
137
                    });
138

    
139
                });
140
                console.log("Selection des fichiers ", selection);
141
            }).catch(function (e) {
142
                console.log("Error ES: " + e);
143
                // process error
144
            });
145

    
146
    }
147

    
148
    onTakePictureTap(args: EventData) {
149
        const options = {
150
            keepAspectRatio: true,
151
            saveToGallery: false
152
        };
153

    
154
        // let button = args.object as Button;
155
        requestCameraPermissions().then(
156
            () => {
157
                takePicture(options)
158
                    .then((imageAsset: any) => {
159
                        let imageSource = new ImageSource();
160

    
161
                        imageSource.fromAsset(imageAsset).then((imageSource) => {
162
                            console.log("ORIG IMAGE SIZE: " + imageSource.height + " x " + imageSource.width);
163
                            console.dir(imageSource);
164
                            // console.log("un ter");
165

    
166
                            this.photoEditor.editPhoto({
167
                                imageSource: imageSource,
168
                                hiddenControls: [
169
                                    PhotoEditorControl.Draw,
170
                                    PhotoEditorControl.Text,
171
                                    PhotoEditorControl.Clear,
172
                                ],
173
                            }).then((newImage: ImageSource) => {
174
                                console.log("NEW IMAGE: ", newImage.height, newImage.width);
175
                                this.imageCropped(newImage);
176
                                // Here you can save newImage, send it to your backend or simply display it in your app
177
                                // this.resultImage.imageSource = newImage;
178
                            }).catch((e) => {
179
                                console.log("erreur 1");
180
                                console.error(e);
181
                            });
182
                            console.log("trois");
183
                        });
184

    
185
                    }, (error) => {
186
                        console.log("Error: " + error);
187
                    });
188
            },
189
            () => alert('permissions rejected')
190
        );
191
    }
192

    
193
    onResetPictureTap(args) {
194
        // this.cameraImage = "res://icon";
195
    }
196

    
197
    onGotoWebTap() {
198
        if (this.album == "") {
199
            dialogs.alert({
200
                title: "Nom d'album",
201
                message: "Il faut renseigner le nom de l'album que vous voulez consulter ...",
202
                okButtonText: "Ok"
203
            }).then(() => {
204
            });
205
        }
206

    
207
        var utilityModule = require("utils/utils");
208
        utilityModule.openUrl("https://" + this.serverURI + "/" + this.album);
209
    }
210

    
211
    onSendPictureTap(args) {
212
        this.enableButtons("btnSendPicture", false)
213
        this.isBusy = true;
214
        let labelObj = <TextField>getViewById(app.getRootView(), "label");
215
        this.label = labelObj.text;
216
        let legendeObj = <TextField>getViewById(app.getRootView(), "legende");
217
        this.legende = legendeObj.text;
218
        let albumObj = <TextField>getViewById(app.getRootView(), "album");
219
        this.album = albumObj.text.toLowerCase().replace(/[^a-z0-9]/g, "");
220
        albumObj = <TextField>getViewById(app.getRootView(), "albumPass");
221
        this.albumPass = albumObj.text;
222

    
223
        console.log("on a maintenant ", this.albumPass);
224

    
225

    
226
        if (this.album == "" || this.label == "") {
227
            dialogs.alert({
228
                title: "Informations manquantes",
229
                message: "Il faut renseigner le nom de l'album auquel vous voulez participer et donner un nom à votre photo ...",
230
                okButtonText: "Ok"
231
            }).then(() => {
232
                this.enableButtons("btnSendPicture", true)
233
                this.isBusy = false;
234
                console.log("clicalbum: album ou label vide");
235
                return;
236
            });
237
        }
238
        else {
239
            setString("album", this.album);
240
            setString("albumPass", this.albumPass);
241
            this.sendPicture(args);
242
        }
243
    }
244

    
245
    sendPicture(args) {
246
        this.enableButtons("btnSendPicture", false)
247
        this.isBusy = true;
248
        // let button = args.object as Button;
249
        const folderPath: string = knownFolders.documents().path;
250
        const fileName = "fichier_temporaire.jpeg";
251
        const filePath = path.join(folderPath, fileName);
252
        let labelObj = <TextField>getViewById(app.getRootView(), "label");
253
        this.label = labelObj.text;
254
        let legendeObj = <TextField>getViewById(app.getRootView(), "legende");
255
        this.legende = legendeObj.text;
256

    
257
        console.log("On voudrait uploader le fichier " + filePath + " dans l'album " + this.album + " sous le nom " + this.label);
258

    
259
        if (this.serverURI == "") {
260
            dialogs.alert({
261
                title: "Serveur ????",
262
                message: "Suite à une collision dans l'espace-temps des nano particules permettant la bonne configuration du logiciel l'adresse du serveur s'est retrouvée vide ... bien entendu ce bug ne devrait pas surgir mais pour continuer vous devrez à nouveau choisir un serveur dans la configuration ... Merci pour votre compréhension",
263
                okButtonText: "Ok"
264
            }).then(() => {
265
                this.enableButtons("btnSendPicture", true)
266
                this.isBusy = false;
267
                console.log("clicalbum: Adresse serveur vide");
268
                return;
269
            });
270
        }
271

    
272
        var url = "https://" + this.serverURI + "/u.php";
273
        console.log("clicalbum: POST vers " + url);
274

    
275
        // // upload configuration
276
        var session = bghttp.session("image-upload");
277
        var request = {
278
            url: url,
279
            method: "POST",
280
            headers: {
281
                "Content-Type": "application/octet-stream",
282
                "User-Agent": "ClicAlbum " + this.appVersion,
283
            },
284
            description: "Uploading " + fileName
285
        };
286

    
287
        var params = [
288
            { name: "login", value: this.base64Encode(this.pseudo) },
289
            { name: "email", value: this.base64Encode(this.email) },
290
            { name: "label", value: this.base64Encode(this.label) },
291
            { name: "legende", value: this.base64Encode(this.legende) },
292
            { name: "album", value: this.base64Encode(this.album) },
293
            { name: "albumPass", value: this.base64Encode(this.albumPass) },
294
            { name: "version", value: "2" },
295
            { name: "fileToUpload", filename: filePath, mimeType: "image/jpeg" }
296
        ];
297
        var task = session.multipartUpload(params, request);
298

    
299
        task.on("progress", logEvent.bind(this));
300
        task.on("error", this.uploadError.bind(this));
301
        task.on("complete", this.uploadCompleted.bind(this));
302
        function logEvent(e) {
303
            console.log("clicalbum: UPLOAD STATUS: " + e.eventName);
304
        }
305
    }
306

    
307
    uploadError(this) {
308
        console.log("clicalbum: UPLOAD ERROR");
309
        dialogs.alert({
310
            title: "Erreur de téléversement",
311
            message: "Pour une raison inconnue le téléversement de votre fichier n'a pas été possible ... si cette erreur persiste merci de nous le signaler via le formulaire de contact disponible sur clicpdf.org",
312
            okButtonText: "Ok"
313
        }).then(() => {
314
            this.enableButtons("btnSendPicture", true)
315
            this.isBusy = false;
316
            console.log("clicalbum: Dialog closed!");
317
        });
318
    }
319

    
320
    uploadCompleted(this) {
321
        console.log("clicalbum: UPLOAD STATUS: terminé");
322
        console.log("clicalbum: UPLOAD STATUS: terminé end");
323
        dialogs.alert({
324
            title: "Téléversement terminé",
325
            message: "Votre document est maintenant sur le serveur",
326
            okButtonText: "Ok"
327
        }).then(() => {
328
            this.isBusy = false;
329
            this.displayImage("");
330
            this.enableButtons("btnSendPicture", false)
331
            console.log("clicalbum: Dialog closed!");
332
        });
333
    }
334

    
335
    saveImage(image, fileName) {
336
        //     // =========== sauvegarde de l'image
337
        if (image.saveToFile(fileName, "jpeg", 95)) {
338
            console.log("clicalbum: Image saved successfully in " + fileName);
339
            this.displayImage(fileName);
340
        }
341
    }
342

    
343
    displayImage(fileName) {
344
        console.log("clicalbum: displayImage  " + fileName);
345
        // if (fileName != "") {
346
            let i = new ImageSource().fromFile(fileName);
347
            this.cameraImage = fileName;
348
        // }
349
        // let i = <Image>getViewById(app.getRootView(), "cameraImage");
350
        // if (i) {
351
        //     console.log("  objet image ok");
352

    
353
        //     if (fileName != "") {
354
        //         i.src = fileName;
355
        //         this.enableButtons("btnSendPicture", true)
356
        //     }
357
        //     else {
358
        //         i.src = "res://icon";
359
        //     }
360
        // }
361

    
362
        this.isBusy = false;
363
        if (fileName != "") {
364
            this.hasPicture = true;
365
        }
366
        else {
367
            this.hasPicture = false;
368
        }
369
        let b = <ActivityIndicator>getViewById(app.getRootView(), "busyIndicator");
370
        if (b) {
371
            console.log("  objet busy ok");
372
            b.busy = false;
373
        }
374

    
375
        console.log("clicalbum: end of displayImage");
376
    }
377

    
378

    
379
    imageCropped(image) {
380
        // this.cameraImage = image;
381
        console.log("imageCropped ...");
382
        console.log("NEW IMAGE: ", image.height, image.width);
383

    
384
        //     // =========== sauvegarde de l'image
385
        const folderPath: string = knownFolders.documents().path;
386
        const fileName = "fichier_temporaire.jpeg";
387
        const filePath = path.join(folderPath, fileName);
388
        this.saveImage(image, filePath)
389
    }
390

    
391
    base64Encode(value) {
392
        console.log("clicalbum: base64 pour " + value);
393
        if (isIOS) {
394
            let text = NSString.stringWithString(value);
395
            let data = text.dataUsingEncoding(NSUTF8StringEncoding);
396
            return data.base64EncodedStringWithOptions(0);
397
        } else {
398
            let text = new java.lang.String(value);
399
            let data = text.getBytes("UTF-8");
400
            return android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
401
        }
402
    }
403

    
404
    onBusyChanged(args: EventData) {
405
        let indicator: ActivityIndicator = <ActivityIndicator>args.object;
406
        console.log("clicalbum: indicator.busy changed to: " + indicator.busy);
407
    }
408

    
409
}
Redmine Appliance - Powered by TurnKey Linux