Projet

Général

Profil

Paste
Statistiques
| Branche: | Révision:

root / src / app / home / home.component.ts @ 2216fd44

Historique | Voir | Annoter | Télécharger (15,2 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 album: string;
37
    public albumPass: string;
38
    private photoEditor;
39
    private appVersion;
40
    public serverName: string;
41
    public serverURI: string;
42
    public hasPicture: boolean;
43
    public isBusy: boolean = true;
44

    
45

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

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

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

    
84

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

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

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

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

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

    
144
    }
145

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

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

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

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

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

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

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

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

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

    
219
        console.log("on a maintenant ", this.albumPass);
220

    
221

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

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

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

    
253
        if (this.serverURI == "") {
254
            dialogs.alert({
255
                title: "Serveur ????",
256
                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",
257
                okButtonText: "Ok"
258
            }).then(() => {
259
                this.enableButtons("btnSendPicture", true)
260
                this.isBusy = false;
261
                console.log("clicalbum: Adresse serveur vide");
262
                return;
263
            });
264
        }
265

    
266
        var url = "https://" + this.serverURI + "/u.php";
267
        console.log("clicalbum: POST vers " + url);
268

    
269
        // // upload configuration
270
        var session = bghttp.session("image-upload");
271
        var request = {
272
            url: url,
273
            method: "POST",
274
            headers: {
275
                "Content-Type": "application/octet-stream",
276
                "User-Agent": "ClicAlbum " + this.appVersion,
277
            },
278
            description: "Uploading " + fileName
279
        };
280

    
281
        var params = [
282
            { name: "login", value: this.base64Encode(this.pseudo) },
283
            { name: "email", value: this.base64Encode(this.email) },
284
            { name: "label", value: this.base64Encode(this.label) },
285
            { name: "album", value: this.base64Encode(this.album) },
286
            { name: "albumPass", value: this.base64Encode(this.albumPass) },
287
            { name: "version", value: "2" },
288
            { name: "fileToUpload", filename: filePath, mimeType: "image/jpeg" }
289
        ];
290
        var task = session.multipartUpload(params, request);
291

    
292
        task.on("progress", logEvent.bind(this));
293
        task.on("error", this.uploadError.bind(this));
294
        task.on("complete", this.uploadCompleted.bind(this));
295
        function logEvent(e) {
296
            console.log("clicalbum: UPLOAD STATUS: " + e.eventName);
297
        }
298
    }
299

    
300
    uploadError(this) {
301
        console.log("clicalbum: UPLOAD ERROR");
302
        dialogs.alert({
303
            title: "Erreur de téléversement",
304
            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",
305
            okButtonText: "Ok"
306
        }).then(() => {
307
            this.enableButtons("btnSendPicture", true)
308
            this.isBusy = false;
309
            console.log("clicalbum: Dialog closed!");
310
        });
311
    }
312

    
313
    uploadCompleted(this) {
314
        console.log("clicalbum: UPLOAD STATUS: terminé");
315
        console.log("clicalbum: UPLOAD STATUS: terminé end");
316
        dialogs.alert({
317
            title: "Téléversement terminé",
318
            message: "Votre document est maintenant sur le serveur",
319
            okButtonText: "Ok"
320
        }).then(() => {
321
            this.isBusy = false;
322
            this.displayImage("");
323
            this.enableButtons("btnSendPicture", false)
324
            console.log("clicalbum: Dialog closed!");
325
        });
326
    }
327

    
328
    saveImage(image, fileName) {
329
        //     // =========== sauvegarde de l'image
330
        if (image.saveToFile(fileName, "jpeg", 95)) {
331
            console.log("clicalbum: Image saved successfully in " + fileName);
332
            this.displayImage(fileName);
333
        }
334
    }
335

    
336
    displayImage(fileName) {
337
        console.log("clicalbum: displayImage  " + fileName);
338
        // if (fileName != "") {
339
            let i = new ImageSource().fromFile(fileName);
340
            this.cameraImage = fileName;
341
        // }
342
        // let i = <Image>getViewById(app.getRootView(), "cameraImage");
343
        // if (i) {
344
        //     console.log("  objet image ok");
345

    
346
        //     if (fileName != "") {
347
        //         i.src = fileName;
348
        //         this.enableButtons("btnSendPicture", true)
349
        //     }
350
        //     else {
351
        //         i.src = "res://icon";
352
        //     }
353
        // }
354

    
355
        this.isBusy = false;
356
        if (fileName != "") {
357
            this.hasPicture = true;
358
        }
359
        else {
360
            this.hasPicture = false;
361
        }
362
        let b = <ActivityIndicator>getViewById(app.getRootView(), "busyIndicator");
363
        if (b) {
364
            console.log("  objet busy ok");
365
            b.busy = false;
366
        }
367

    
368
        console.log("clicalbum: end of displayImage");
369
    }
370

    
371

    
372
    imageCropped(image) {
373
        // this.cameraImage = image;
374
        console.log("imageCropped ...");
375
        console.log("NEW IMAGE: ", image.height, image.width);
376

    
377
        //     // =========== sauvegarde de l'image
378
        const folderPath: string = knownFolders.documents().path;
379
        const fileName = "fichier_temporaire.jpeg";
380
        const filePath = path.join(folderPath, fileName);
381
        this.saveImage(image, filePath)
382
    }
383

    
384
    base64Encode(value) {
385
        console.log("clicalbum: base64 pour " + value);
386
        if (isIOS) {
387
            let text = NSString.stringWithString(value);
388
            let data = text.dataUsingEncoding(NSUTF8StringEncoding);
389
            return data.base64EncodedStringWithOptions(0);
390
        } else {
391
            let text = new java.lang.String(value);
392
            let data = text.getBytes("UTF-8");
393
            return android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
394
        }
395
    }
396

    
397
    onBusyChanged(args: EventData) {
398
        let indicator: ActivityIndicator = <ActivityIndicator>args.object;
399
        console.log("clicalbum: indicator.busy changed to: " + indicator.busy);
400
    }
401

    
402
}
Redmine Appliance - Powered by TurnKey Linux